python多进程 multiprocessing.pipe 管道没有数据接收端会卡死,无提示,无报错!!!

python多进程 multiprocessing.pipe 使用管道通信的生产者进程和消费者进程必须同时运行。

测试发现,没有生产时,消费也不运行。

例如:如下程序中,生产者在计数为10-30之间不发送数据,但是消费者也不会运行(没有输出)。

为什么?接收端不是没有运行,而是它还卡在10的那个地方等到接收数据、没有往下继续运行!!!!参考我的这篇博客中的第2种情况

更严重的是,这个不属于异常,无法捕获!接收端的程序无法往下运行!!(在下一个发送端发送的数据到来之前)

解决方法:老兄,如果你没有好的解决方法就改用multiprocessing.Manager的队列吧!Manager.Queue()大法好!

你有好的办法?欢迎告诉我!!!

以下代码符合PEP8规范。(之前被人吐槽过代码乱,让人没有想看的欲望。。。)

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()
发布了202 篇原创文章 · 获赞 80 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/qxqxqzzz/article/details/105104408