【发布时间】:2017-11-19 14:23:40
【问题描述】:
我有 2 个进程 P1 和 P2 的模拟。有 2 个资源,R1 和 R2。
P1 使用 R1 表示 20',R2 表示 10' P2 使用 R2 10'
我想使用 SimPy 实现以下逻辑,需要一些指导:
If R2 is free:
run P2
If R1 and R2 are free:
run P1
谢谢!
【问题讨论】:
我有 2 个进程 P1 和 P2 的模拟。有 2 个资源,R1 和 R2。
P1 使用 R1 表示 20',R2 表示 10' P2 使用 R2 10'
我想使用 SimPy 实现以下逻辑,需要一些指导:
If R2 is free:
run P2
If R1 and R2 are free:
run P1
谢谢!
【问题讨论】:
SimPy 提供的是resource.request()。
这是第一种情况的一个小例子。
resource_free = yield my_resource.request()
if my_resource_request() in resource_free:
TODO: P1.run()
我们在这里所做的是我们正在请求资源。当资源产生时,它就可以免费使用了,我们将其放入resource_free。
【讨论】:
您需要查询您的资源发生了什么。
让我们将您的资源定义为:
R1 = simpy.Resource(env, capacity = 1)
R2 = simpy.Resource(env, capacity = 1)
您可以就这些资源的可用性提出问题,如下所示:
# Number of users currently using the resources.
num_users_R1 = R1.count()
num_users_R2 = R2.count()
现在您知道了这一点,您可以使用 if 语句来告诉 sim 遵循哪些流程。
# if both are free do process 1
if num_users_R2 + num_users_R2 == 2:
process_1()
# otherwise do process 2
else:
process_2()
更多关于资源命令的内容可以阅读官方文档:http://simpy.readthedocs.io/en/latest/api_reference/simpy.resources.html
【讨论】: