我有一台服务器,一次最多可以服务3个客户。我将其建模为带有Resource
的SimPy capacity=3
,如下所示。 如何更新我的代码,以便每当有新客户到达时,如果服务器的所有容量都被利用,新客户就会被遗忘?
我已经阅读了文档,但是找不到适合这种情况的示例。
SERVERS= 3
class Servers:
def __init__(self, env):
self.cashier = simpy.Resource(env, capacity= SERVERS)
def Customer(name, env, servers):
print('Customer %s arriving at %s' % (name, env.now))
with servers.cashier.request() as req:
yield req
print('Customer %s starts being served at %s' % (name, env.now))
yield env.timeout(35)
print('Customer %s done served at %s' % (name, env.now))
def customer_generator(env, servers):
for i in range(100):
env.process(Customer(i, env, servers))
yield env.timeout(5)
env = simpy.Environment()
servers = Servers(env)
cus_generator = env.process(customer_generator(env, servers))
env.run(1000)
答案 0 :(得分:0)
SimPy提供了一种简单的方法来检查当前正在使用多少资源的容量。可以使用<resource>.count
(link to API)来完成。
您的示例可以进行如下修改:
SERVERS= 3
class Servers:
def __init__(self, env):
self.cashier = simpy.Resource(env, capacity= SERVERS)
def Customer(name, env, servers):
print('Customer %s arriving at %s' % (name, env.now))
# check if any of the cashiers are free:
if servers.cashier.count < servers.cashier.capacity:
with servers.cashier.request() as req:
yield req
print('Customer %s starts being served at %s' % (name, env.now))
yield env.timeout(35)
print('Customer %s done served at %s' % (name, env.now))
else:
print('Customer %s leaving as there was no cashier free to serve them' % (name))
def customer_generator(env, servers):
for i in range(100):
env.process(Customer(i, env, servers))
yield env.timeout(5)
env = simpy.Environment()
servers = Servers(env)
cus_generator = env.process(customer_generator(env, servers))
env.run(1000)
请注意,随着该函数的结束,客户流程将自动在else
分支中被销毁(被遗忘),而无需点击其他yield
。