温馨提示×

Python中Process如何通信

小樊
92
2024-08-02 07:54:08
栏目: 编程语言

在Python中,可以使用multiprocessing模块中的Queue、Pipe、Manager等方式来实现多个进程之间的通信。

  1. 使用Queue:
from multiprocessing import Process, Queue

def worker(q):
    data = q.get()
    print(f"Received data: {data}")

if __name__ == '__main__':
    q = Queue()
    
    p = Process(target=worker, args=(q,))
    p.start()
    
    q.put("Hello from main process")
    
    p.join()
  1. 使用Pipe:
from multiprocessing import Process, Pipe

def worker(conn):
    data = conn.recv()
    print(f"Received data: {data}")
    conn.send("Hello from worker")

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    
    p = Process(target=worker, args=(child_conn,))
    p.start()
    
    parent_conn.send("Hello from main process")
    print(parent_conn.recv())
    
    p.join()
  1. 使用Manager:
from multiprocessing import Process, Manager

def worker(d):
    d["key"] = "value"
    print(f"Worker data: {d}")

if __name__ == '__main__':
    with Manager() as manager:
        d = manager.dict()
        
        p = Process(target=worker, args=(d,))
        p.start()
        
        p.join()
        
        print(f"Main process data: {d}")

这些方法可以让不同进程之间进行数据的传递和共享,从而实现进程间的通信。

0