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
但正如上面提到的,我應該得到的。作者應該等到讀者準備好閱讀。
非常感謝您的回答。但是讀者和寫作者的過程應該彼此等待。這不會發生,對吧?我想作家會繼續,儘管它應該等到讀者準備閱讀。 –
非常感謝。基本上這是我需要的。現在我將考慮編寫自己的資源類型。但首先,我必須更多地瞭解Simpy以及一般的Python。如果您對我需要的資源類型有任何建議,我將非常感激。 –
我會繼續使用它,直到你感覺更加友好和熟悉Python和SimPy。然後,我會寫一個Store的子類來完成你想要的任務。另外,閱讀所有的SimPy文檔。 ;-) –