Python3下multiprocessing多进程实现,并用Pipe实施进程间通信

本文展示了一个使用Python的multiprocessing模块进行多进程通信的示例。通过Pipe对象实现进程间的数据发送与接收,演示了如何在一个进程中生成数据,并在另一个进程中处理这些数据。此示例适用于希望了解Python多进程及进程间通信机制的读者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

'''
An SIMPLE, BRUTAL Demostration for multiprocessing on Python3.
Pipe used for interprocess communications.

Tips:
    Run this demo in a shell to get the messages printed.
    This demo shows nothing if you run it in idle3 or spyder3.
'''

from multiprocessing import Process, Pipe
import time


def Motion(conn_motion):
    '''
    Data generator/sender 1.
    '''
    while True:
        s = "motion function %s"%time.ctime()
        print('>>>>', s)
        conn_motion.send(s)
        time.sleep(1.3)
        

def GPS(conn_gps):
    '''
    Data generator/sender 2.
    '''
    while True:
        s = "gps    function %s"%time.ctime()
        print('>>>>', s)
        conn_gps.send(s)
        
        time.sleep(2.3)
        

def Worker(conn_motion, conn_gps):
    '''
    Data receiver/processer.
    '''
    while True:
        print('-'*40)
        if conn_motion.poll(): # to avoid blocking of recv.
            s = conn_motion.recv()
            print('<<<<', s)
            
        if conn_gps.poll():
            s = conn_gps.recv()
            print('<<<<', s)

        time.sleep(0.1)
        

def Main():
    conn_motion_1, conn_motion_2 = Pipe()
    conn_gps_1,    conn_gps_2    = Pipe()

    p_motion = Process(target=Motion, args=(conn_motion_1,))
    p_gps    = Process(target=GPS,    args=(conn_gps_1,))
    p_worker = Process(target=Worker, args=(conn_motion_2, conn_gps_2,))

    p_motion.start()
    p_gps.start()
    p_worker.start()

    p_motion.join()
    p_gps.join()
    p_worker.join()
    
if __name__ == '__main__':
    Main()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值