在Python中,可以使用multiprocessing模块中的Queue、Pipe、Manager等方式来实现多个进程之间的通信。
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()
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()
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}")
这些方法可以让不同进程之间进行数据的传递和共享,从而实现进程间的通信。