2016-03-24 51 views
0

我是一個開始使用Python和Simpy的新手。我想在兩個進程之間有一個同步通信通道。例如,我想有: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

你想要的內容不是直接可用的。一種解決方法可能如下:

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 

另一種方法是寫你的自己的資源類型。

+0

非常感謝您的回答。但是讀者和寫作者的過程應該彼此等待。這不會發生,對吧?我想作家會繼續,儘管它應該等到讀者準備閱讀。 –

+0

非常感謝。基本上這是我需要的。現在我將考慮編寫自己的資源類型。但首先,我必須更多地瞭解Simpy以及一般的Python。如果您對我需要的資源類型有任何建議,我將非常感激。 –

+0

我會繼續使用它,直到你感覺更加友好和熟悉Python和SimPy。然後,我會寫一個Store的子類來完成你想要的任務。另外,閱讀所有的SimPy文檔。 ;-) –