Skip to content Skip to sidebar Skip to footer

How To Know Which Resource Is Being Used When Using Simpy's Anyof Method?

In my program, agents need to use some specific resources. I want to call all of the resources that are assigned for an agent at the same time and use the first available one. Thin

Solution 1:

env.any_of returns a dict of the first events that fired. Remember that both events can fire at the same time. Also remember that if only one event fires, the second event is still pending. So if you only want one event to fire you will have to check if both events fired and release one, or if only one event fired, to cancel the second event.

here is a example

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

prorammer Michael R. Gibbs
"""import simpy

defseat(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 poolsprint(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]

    iflen(seatList) > 1:
        # both requests got filled, need to release oneprint(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 requestprint(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")

deftest(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')

Post a Comment for "How To Know Which Resource Is Being Used When Using Simpy's Anyof Method?"