在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: aegqsqibtmh")
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: aegqsqibtmh")
這些方法可以讓不同進程之間進行數據的傳遞和共享,從而實現進程間的通信。