使用 SimPy 的 AnyOf 方法时如何知道正在使用哪个资源?

How to know which resource is being used when using SimPy's AnyOf method?

在我的程序中,代理需要使用一些特定资源。我想同时调用分配给代理的所有资源并使用第一个可用的资源。

考虑 3 个服务器和 4 个代理。

agent1可以用server1,

agent2 可以使用 server1server2,

agent3 可以使用 server2server3,

agent4 可以用 server3

我正在创建如下请求:

{server: server.request() for server in agent_2_server_list}

output:
{<simpy.resources.resource.Resource at 0x7fd091b215e0>: <Request() object at 0x7fd091d51d00>,
 <simpy.resources.resource.Resource at 0x7fd091b21700>: <Request() object at 0x7fd091d51b50>}

我正在使用 env.any_of([request1, request2]) 来使用上述任何请求。但是,我需要知道使用了哪个资源,以便之后可以释放它。我该怎么做?

env.any_of returns 触发的第一个事件的命令。请记住,这两个事件可以同时触发。还要记住,如果只有一个事件触发,则第二个事件仍未决。因此,如果您只想触发一个事件,则必须检查是否触发了两个事件并释放一个事件,或者如果只触发了一个事件,则取消第二个事件。

这里有一个例子

"""
example of getting the first avalable resouce from 2 resouce pools

prorammer Michael R. Gibbs
"""
import simpy

def seat(env, id, smokingRes, nonSmokingRes):
    """
    Main process of getting the first avaialbe table
    from one of two resouce pools (smoking, non smoking)
    """

    # make a request from both resouce pools
    print(env.now, id, "waiting for a table")
    smokeReq = smokingRes.request()
    nonSmokeReq = nonSmokingRes.request()

    # wait for one of the requests to be filled
    seat = yield env.any_of([smokeReq,nonSmokeReq])
    
    seatList = list(seat.keys())

    # it is possible that both resources are avaliable
    # and both request get filled
    seated = seatList[0]

    if len(seatList) > 1:
        # both requests got filled, need to release one
        print(env.now, id, "both were available, releasing one")
        if seated == smokeReq:
            nonSmokingRes.release(nonSmokeReq)
        else:
            smokingRes.release(smokeReq)
    else:
        # only one request was filled, need to cancel the other request
        print(env.now, id, 'got a seat, cancel other request')
        if smokeReq in seatList:
            nonSmokeReq.cancel()
        else:
            smokeReq.cancel()

    yield env.timeout(5)
    if seated == smokeReq:
        smokingRes.release(seated)
    else:
        nonSmokingRes.release(seated)
    print(env.now, id, "released seat")

def test(env, smokingRes, nonSmokingRes):
    """
    test when four people want 2 tables
    """
    env.process(seat(env,1,smokingRes,nonSmokingRes))
    yield env.timeout(1)
    env.process(seat(env,2,smokingRes,nonSmokingRes))
    yield env.timeout(1)
    env.process(seat(env,3,smokingRes,nonSmokingRes))
    yield env.timeout(1)
    env.process(seat(env,4,smokingRes,nonSmokingRes))


env = simpy.Environment()
smokingRes = simpy.Resource(env, capacity=1)
nonSmokingRes = simpy.Resource(env, capacity=1)

env.process(test(env,smokingRes,nonSmokingRes))


env.run(until=100)

print ('done')