Python进程之间的信息传递

方法一:使用Queue

from multiprocessing import Process,Queue

def f(q,n):
    q.put([42,n,'hello'])

if __name__ == '__main__':
    q=Queue()
    p_list = []
    q.put(333)
    for i in range(3):
        p = Process(target=f,args=(q,1))
        p_list.append(p)
        p.start()
    print(q.get())
    print(q.get())
    print(q.get())

    for i in p_list:
        i.join()
方法二:使用Pipe
from multiprocessing import Process,Pipe

def f(conn):
    conn.send("约吗")
    conn.send("约吗")
    print(conn.recv())
    conn.close()

if __name__ == "__main__":
    parent_conn,child_conn = Pipe()
    p = Process(target=f,args=(child_conn,))
    p.start()
    print(parent_conn.recv())
    print(parent_conn.recv())
    parent_conn.send("约!")
    p.join()

使用manager实现进程之间的数据共享

from multiprocessing import Process,Manager

def f(d,l,n):
    d[n] = '1'
    d['2'] = 2
    d[0.25] = None
    l.append(n)
    print(l)

if __name__ == '__main__':
    with Manager() as manager:
        d = manager.dict()
        l = manager.list(range(5))
        p_list = []
        for i in range(10):
            p = Process(target=f,args=(d,l,i))
            p.start()
            p_list.append(p)

        for p in p_list:
            p.join()

        print(d)
        print(l)

 

你可能感兴趣的:(Python,个人学习笔记)