我是一个刚开始使用Python和Simpy的新手。我想在两个进程之间建立一个同步通信通道。例如,我想:
channel = ...
def writer(env):
for i in range(2):
yield env.timeout(0.75)
yield channel.put(i)
print("produced {} at time {}".format(i, env.now))
def reader(env):
while (True):
yield env.timeout(1.2)
i = yield channel.get()
print("consumed {} at time {}".format(i, env.now))
env = simpy.Environment()
env.process(writer(env))
env.process(reader(env))
env.run()
它应该给出结果:
produced 0 at time 1.2
consumed 0 at time 1.2
produced 1 at time 2.4
consumed 1 at time 2.4
我应该如何制作/使用频道定义?
如果我使用的Store
比我得到的(与上面略有不同):
import simpy
env = simpy.Environment()
channel = simpy.Store(env)
def writer():
for i in range(2):
yield env.timeout(0.75)
yield channel.put(i)
print("produced {} at time {}".format(i, env.now))
def reader():
while (True):
yield env.timeout(1.2)
i = yield channel.get()
print("consumed {} at time {}".format(i, env.now))
env.process(writer())
env.process(reader())
env.run()
,输出为:
produced 0 at time 0.75
consumed 0 at time 1.2
produced 1 at time 1.5
consumed 1 at time 2.4
但我应该如上所述。作者应该等到读者准备好阅读。
答案 0 :(得分:0)
使用内置资源无法直接获得所需内容。解决方法可能如下:
import collections
import simpy
Message = collections.namedtuple('Message', 'received, value')
def writer(env, channel):
for i in range(2):
yield env.timeout(0.75)
msg = Message(env.event(), i)
yield channel.put(msg)
yield msg.received
print("produced {} at time {}".format(i, env.now))
def reader(env, channel):
while (True):
yield env.timeout(1.2)
msg = yield channel.get()
msg.received.succeed()
print("consumed {} at time {}".format(msg.value, env.now))
env = simpy.Environment()
channel = simpy.Store(env, capacity=1)
env.process(writer(env, channel))
env.process(reader(env, channel))
env.run()
输出:
consumed 0 at time 1.2
produced 0 at time 1.2
consumed 1 at time 2.4
produced 1 at time 2.4
如果您在print()
之前执行yield msg.received
,您将获得:
produced 0 at time 0.75
consumed 0 at time 1.2
produced 1 at time 1.95
consumed 1 at time 2.4
另一种方法是编写自己的资源类型。