【发布时间】:2018-01-30 02:08:20
【问题描述】:
我想要两个并行运行的进程。一个从另一个获取输入,处理数据并将处理后的数据作为输出发送回另一个。另一个进程做同样的事情。显然需要有起点和终点。
如何在进程运行时在它们之间进行通信?我只设法依次运行这两个进程。
我尝试用multiprocessing解决它:
from multiprocessing import Process, Queue, Array
sentinel = -1
def process1(q, arr):
# Receives data, modifies it and sends it back
while True:
data = q.get() # Receive data
if data is sentinel:
break
data *= 2 # Data modification
arr.append(data) # Data logging
q.put(data) # Send data
q.put(sentinel) # Send end signal
def process2(q, arr):
# Receives data, increments it and sends data back
if q.empty():
data = 1
else:
while True:
data = q.get() # Receive data
if data == sentinel:
break
data += 1
q.put(data) # Send data
arr.append(data) # Data logging
q.put(sentinel) # Send end signal
if __name__ == "__main__":
q = Queue()
logbook = Array('i', 0)
counter = 0
while counter < 10:
process_1 = Process(target=process1, args=(q, logbook))
process_2 = Process(target=process2, args=(q, logbook))
process_1.start()
process_2.start()
q.close()
q.join_thread()
process_1.join()
process_2.join()
counter += 1
print(logbook)
【问题讨论】:
-
使用异步
-
@danihp RFM 是什么意思?
-
我的意思是RTFM,但不是进程间通信系统。
标签: python python-3.x multiprocessing