0
我正在学习Python多处理管道。我的目标是两个独立的进程,其中一个发送另一个消息五次。我运行它没有问题,但它只是显示它们的PID,就是这样。这段代码我错了什么?我的环境是Windows 10(64位)和Python 3.6.1(32位)。我不明白为什么这段代码不起作用(multiprocessing.Pipe)
import os
import multiprocessing as mp
import time
global sending_end, receiving_end
sending_end, receiving_end = mp.Pipe()
def sender(sending_end=sending_end):
print('SND PID: ', os.getpid())
for _ in range(5):
sending_end.send('test')
time.sleep(1)
class receiver(mp.Process):
def __init__(self):
mp.Process.__init__(self)
def run(self, receiving_end=receiving_end):
print('REC PID: ', os.getpid())
print(receiving_end.recv())
time.sleep(1)
if __name__ == '__main__':
print('MAIN PID: ', os.getpid())
s = mp.Process(target = sender, args=(sending_end,))
s.start()
r = receiver()
r.start()
mp.freeze_support()
为什么要使用管道?有一个[队列](https://docs.python.org/3.3/library/multiprocessing.html?highlight=multiprocessing#exchanging-objects-between-processes),它为你做了所有的事情。 – uphill
@uphill我认为使用管道将更加兼容,以防在进程间双向交换消息的机会。 – maynull
如果你没有使用python作为其他进程,你可能会考虑[subprocess](https://docs.python.org/3/library/subprocess.html?highlight=subprocess#module-subprocess),因为mutliprocessing是一个drop通过产生更多的python进程来替代使用多个cpu来避免GIL。 – uphill