我正在研究Python多处理管道。我的目标是两个独立的进程,其中一个进程发送另一个消息五次。我没有运行它的问题,但它只是显示他们的PID,就是这样。这段代码我错了什么?我的环境是Windows 10(64位)和Python 3.6.1(32位)。
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()
答案 0 :(得分:0)
您似乎忘记调用继承run()
类(PARENT)的receiver
类(CHILD)的multiprocessing.Process
方法。
由于未明确调用run()
,因此调用了父run()
方法,并且它没有您的接收值打印代码。因此,它感觉代码没有运行。
还有一些事情:
run()
方法,直到发送进程处于活动状态。请检查以下代码,并注明以上几点。
<强>代码:强>
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 i in range(5):
sending_end.send('test_' + str(i) )
time.sleep(1)
print "Done from sender"
#Closing sending pipe
sending_end.close()
class receiver(mp.Process):
def __init__(self):
mp.Process.__init__(self)
def run(self, receiving_end=receiving_end):
print('REC PID: ', os.getpid() )
print( "Dinesh - ",receiving_end.recv() )
time.sleep(1)
if __name__ == '__main__':
import sys
print('MAIN PID: ', os.getpid() )
s = mp.Process( target = sender, args=(sending_end,) )
s.start()
r = receiver()
r.start()
while True:
#Checking sending process is alive or not
if not s.is_alive():
print "Sending process is done. Exiting"
#Closing receiving end pipe
receiving_end.close()
#Closing receving process
r.terminate()
sys.exit()
time.sleep(0.1)
#Explicitly calling run method
r.run()
mp.freeze_support()
<强>输出:强>
('MAIN PID: ', 16400)
('REC PID: ', 16400)
('REC PID: ', 12544)
('SND PID: ', 17744)
('Dinesh - ', 'test_0')
('REC PID: ', 16400)
('Dinesh - ', 'test_1')
('REC PID: ', 16400)
('Dinesh - ', 'test_2')
('REC PID: ', 16400)
('Dinesh - ', 'test_3')
('REC PID: ', 16400)
('Dinesh - ', 'test_4')
Done from sender
Sending process is done. Exiting