Python multiprocessing multiprocessing.pipe producer and consumer processes that use pipe communication must run simultaneously.
Tests have found that when there is no production, consumption does not run.
For example: in the following program, the producer does not send data between 10-30 counts, but the consumer will not run (no output).
why? The receiving end is not not running , but it is still stuck at the place where 10 waits to receive data and does not continue to run down! ! ! ! Refer to the second situation in my blog
More seriously, this is not an exception and cannot be captured! The program on the receiving end cannot run down! ! (Before the data from the next sender arrives)
Solution: Dude, if you don't have a good solution, use multiprocessing.Manager's queue instead! Manager.Queue () Dafa is good!
Do you have a good way? Welcome to tell me! ! !
The following code conforms to the PEP8 specification. (Before I was confessed that the code was messy, people had no desire to read ...)
import time
from multiprocessing import Pipe, Process
def sed_fun(p_conn):
all_sed = 0
s, r = p_conn
send_num = 0
while True:
time.sleep(1)
all_sed += 1
print('sending...', all_sed)
try:
send_num += 1
print('try to send', send_num)
if send_num < 10:
msg = 1111
print('sending', msg)
s.send([msg])
elif send_num > 30:
msg = 2222
print('sending', msg)
s.send([msg])
else:
print('no send any more')
# sed.close() # uncomment will cause the sed proc not to be resurrected after 30
except Exception as e:
print(e)
print('can not send')
def rec_fun(p_conn):
all_rec = 0
s, r = p_conn
while True:
time.sleep(1)
all_rec += 1
print('\nreceiving.....', all_rec)
try:
print('\n', r.recv()) # If there is no data in pipe, it will be stuck here with no notification!!!
except Exception as e: # this except has no use when stucked above!
print(e)
print('can not recv')
if __name__ == '__main__':
sed, rec = Pipe()
sed_proc = Process(target=sed_fun, args=((sed, rec), ))
rec_proc = Process(target=rec_fun, args=((sed, rec), ))
sed_proc.start()
rec_proc.start()
sed_proc.join()
rec_proc.join()