您可能想使用
multiprocessing.Queue
,您可以在其中轻松地转储对象而不必担心类型。它也是线程安全和进程安全的。
以下是一个简单的示例,使用队列解决生产者-消费者问题(
原始来源,Pizza是我添加的额外奖励)。
from multiprocessing import Process, Queue
class Pizza(object):
def __init__(self, pizza_num):
self.pizza_num = pizza_num
self.num_slices = 8
sentinel = "NO PIZZA"
def producer(initial_num_pizzas, total_num_pizzas, q):
"""Cooks Pizzas to be consumed and waits for the consumer to finish eating."""
print("Producer: I am cooking %s Pizzas and putting them on the Queue!"%(total_num_pizzas-initial_num_pizzas))
for i in range(q.qsize(), total_num_pizzas):
print("Producer: Behold, for I have cooked Pizza no. %s"%i)
q.put(Pizza(i))
q.put(sentinel)
def consumer(q):
"""Consumes some Pizza. In this case, all it does is set the number of slices to 0."""
while True:
pizza = q.get()
pizza.num_slices = 0
if pizza == sentinel:
break
print("Comsumer: Pizza no. %s was found! It has %s slices, yum!"%(pizza.pizza_num, pizza.num_slices))
if __name__ == '__main__':
q = Queue()
total_num_pizzas = 10
initial_num_pizzas = 4
for i in range(0, initial_num_pizzas):
q.put(Pizza(i))
print("Main: I have precooked %s Pizzas."%q.qsize())
producer_proc = Process(target=producer, args=(initial_num_pizzas, total_num_pizzas, q))
consumer_proc = Process(target=consumer, args=(q,))
producer_proc.start()
consumer_proc.start()
q.close()
q.join_thread()
producer_proc.join()
consumer_proc.join()
以下是一个输出示例。如果您运行它,由于并行进程的非确定性执行,生产者和消费者的打印语句可能会以不同的方式交错出现。
Main: I have precooked 4 Pizzas.
Producer: I am cooking 6 Pizzas and putting them on the Queue!
Producer: Behold, for I have cooked Pizza no. 4
Producer: Behold, for I have cooked Pizza no. 5
Producer: Behold, for I have cooked Pizza no. 6
Producer: Behold, for I have cooked Pizza no. 7
Comsumer: Pizza no. 0 was found! It has 8 slices, yum!
Comsumer: Pizza no. 1 was found! It has 8 slices, yum!
Producer: Behold, for I have cooked Pizza no. 8
Comsumer: Pizza no. 2 was found! It has 8 slices, yum!
Producer: Behold, for I have cooked Pizza no. 9
Comsumer: Pizza no. 3 was found! It has 8 slices, yum!
Comsumer: Pizza no. 4 was found! It has 8 slices, yum!
Comsumer: Pizza no. 5 was found! It has 8 slices, yum!
Comsumer: Pizza no. 6 was found! It has 8 slices, yum!
Comsumer: Pizza no. 7 was found! It has 8 slices, yum!
Comsumer: Pizza no. 8 was found! It has 8 slices, yum!
Comsumer: Pizza no. 9 was found! It has 8 slices, yum!
请注意,您应该
使用哨兵标记队列的结尾。我在这里使用了“NO PIZZA”,但它们可以是任何东西。