简单的同步通信通道

Simpy synchronous communication channel

我是刚开始使用 Python 和 Simpy 的新手。我想在 2 个进程之间有一个 synchronous 通信通道。例如我想要:

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

通道的定义应该make/use什么?

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

但是我应该按照上面说的那样得到。作者应该等到 reader 准备好阅读。

内置资源无法直接实现您想要的。解决方法可能如下:

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

如果您在 yield msg.received 之前执行 print(),您将得到:

produced 0 at time 0.75
consumed 0 at time 1.2
produced 1 at time 1.95
consumed 1 at time 2.4

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