python multiprocessing 进程间交换对象的应用
时间: 2023-12-08 07:20:45 浏览: 260
在Python中,可以使用multiprocessing模块创建进程来并行处理任务,同时也可以使用该模块提供的Queue来实现多进程之间的数据共享和通信。下面是一个简单的例子,演示了如何在多个进程之间共享数据:
```python
import multiprocessing
def producer(queue):
for i in range(10):
queue.put(i)
def consumer(queue):
while True:
item = queue.get()
if item is None:
break
print(item)
if __name__ == '__main__':
queue = multiprocessing.Queue()
p1 = multiprocessing.Process(target=producer, args=(queue,))
p2 = multiprocessing.Process(target=consumer, args=(queue,))
p1.start()
p2.start()
p1.join()
queue.put(None)
p2.join()
```
在这个例子中,我们创建了一个Queue对象,并将其传递给两个进程。生产者进程通过put()方法将10个整数放入队列中,而消费者进程则不断地从队列中取出数据并打印。注意到我们在队列的末尾放了一个None对象,以此来告诉消费者进程已经没有数据可取了,可以结束了。
除了Queue之外,还可以使用multiprocessing模块提供的Pipe来实现进程间的通信。Pipe函数返回一对连接对象,分别代表管道的两端。我们可以通过这些连接对象向管道中发送和接收数据。下面是一个例子:
```python
import multiprocessing
def child(conn):
conn.send([42, None, 'hello'])
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = multiprocessing.Pipe()
p = multiprocessing.Process(target=child, args=(child_conn,))
p.start()
print(parent_conn.recv()) # prints "[42, None, 'hello']"
p.join()
```
在这个例子中,我们创建了两个进程之间的管道,并将管道的一端传递给子进程。子进程通过send()方法向管道中发送一个列表,包含一个整数、一个None对象和一个字符串。父进程则通过recv()方法从管道中读取数据,打印出刚才子进程发送的列表。
阅读全文
相关推荐


















