0

我是一个开始使用 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

我应该为频道的定义制作/使用什么?

如果我使用 a 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

但我应该得到如上所述的。作者应该等到读者准备好阅读。

4

1 回答 1

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()before 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

另一种方法是编写自己的资源类型。

于 2016-03-25T07:50:51.270 回答