Python 多进程_通信

1. 多进程队列  , 只能实现数据交互,不能共享

from multiprocessing import Process,Queue
import time
import  uuid

class MyProcess(Process):

    def __init__(self,q):
        super(MyProcess,self).__init__()
        self.q=q

    def run(self):
        self.q.put(uuid.uuid1())

if __name__ == '__main__':

    q=Queue()  # 进程队列

    """由于每个进程都是独立的空间,所以必须将一个队列传入到每个进程里面共享"""
    p = MyProcess(q)
    p2= MyProcess(q)

    p.start()
    p2.start()

    print(q.get())
    print(q.get())

 

2. 双向管道,只能实现数据交互,不能共享

from multiprocessing import Process,Queue,Pipe
import time
import  uuid


class MyProcess(Process):

    def __init__(self,conn):
        super(MyProcess,self).__init__()
        self.conn=conn

    def run(self):
        self.conn.send('hello')

        data=self.conn.recv() # 没有 send之前阻塞
        print(data)

if __name__ == '__main__':

    conn1,conn2=Pipe()  # 管道

    """由于每个进程都是独立的空间,所以必须将一个队列传入到每个进程里面共享"""
    p = MyProcess(conn1)
    p.start()
    #======================================
    data = conn2.recv()  # 没有 send之前阻塞
    print(data)
    conn2.send('ok')

3. Managers, 支持数据共享

from multiprocessing import Process,Queue,Pipe,Manager
import time
import  uuid


class MyProcess(Process):

    def __init__(self,dic,li,num):
        super(MyProcess,self).__init__()
        self.dic=dic
        self.li=li
        self.num=num

    def run(self):
        self.dic['num%s'%self.num]=self.num
        self.li.append(self.num)

if __name__ == '__main__':

    with Manager() as manager:
        dic=manager.dict()  # 创建多进程共享字典
        li =manager.list()  # 创建多进程共享列表

        process_list=[]

        for i  in range(5):
            p=MyProcess(dic,li,i)
            p.start()
            process_list.append(p)

        for p in process_list:
            p.join()

        print(dic)
        print(li)

 

 

 

 

 

 

 

4.

5.

6.

7.

8.

9.

posted @ 2021-01-11 20:26  leungqingyun  阅读(122)  评论(0编辑  收藏  举报