在Python中,多进程编程可以通过multiprocessing
模块实现。为了在进程之间进行通信,multiprocessing
模块提供了几种进程间通信(IPC)机制,包括管道(Pipe)、队列(Queue)、共享内存(Value, Array)和消息传递(Manager)。下面是一些示例:
- 管道(Pipe):
from multiprocessing import Process, Pipe def sender(conn): conn.send(['Hello', 'from', 'sender']) conn.close() def receiver(conn): message = conn.recv() print('Received:', message) conn.close() if __name__ == '__main__': parent_conn, child_conn = Pipe() p1 = Process(target=sender, args=(child_conn,)) p2 = Process(target=receiver, args=(parent_conn,)) p1.start() p2.start() p1.join() p2.join()
- 队列(Queue):
from multiprocessing import Process, Queue def worker(q): q.put('Hello from worker') if __name__ == '__main__': q = Queue() p = Process(target=worker, args=(q,)) p.start() print(q.get()) p.join()
- 共享内存(Value, Array):
from multiprocessing import Process, Value, Array import ctypes def worker(num): num.value += 1 if __name__ == '__main__': num = Value(ctypes.c_int, 0) p = Process(target=worker, args=(num,)) p.start() p.join() print(num.value)
- 消息传递(Manager):
from multiprocessing import Process, Manager def worker(d): d['key'] = 'Hello from worker' if __name__ == '__main__': with Manager() as manager: d = manager.dict() p = Process(target=worker, args=(d,)) p.start() print(d['key']) p.join()
这些示例展示了如何使用不同的IPC机制在多进程Python程序中进行通信。你可以根据你的需求选择合适的通信方式。