"""
example of getting the first available resource from 2 resource pools
programmer 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')