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