进程队列的基本用法
from multiprocessing import Process, Queue
import queue
q = Queue(2) # 队列容量为2
q.put(1)
q.put(2)
try:
q.put_nowait(3) # 非阻塞的方法,如果队列满了,就报错
except queue.Full:
print('the queue only contain 2 ')
print(q.get())
print(q.get())
try:
print(q.get_nowait()) # # 非阻塞的方法,如果队列满了,就报错
except queue.Empty:
print('the queue is empty')
print(q.empty()) # 判断队列是否为空
print(q.full())
运行结果
the queue only contain 2
1
2
the queue is empty
True
False
多进程间的队列
from multiprocessing import Process,Queue
def consume(q):
print(q.get()) # 子进程取
if __name__ == '__main__':
q = Queue()
p = Process(target=consume, args=(q,))
p.start()
q.put({
'123': 123}) # 主进程放数据
运行结果
{
'123': 123}
由于该模块队列间使用socket和pickle来实现数据的传输,所以python中的任何数据都可以传。
生产者消费者模型
import time
import random
from multiprocessing import Process,Queue
def consumer(q, name):
while True:
food = q.get()
if food is None: break
time.sleep(random.uniform(0.5, 1))
print('%s吃了一个%s' % (name, food))
def producer(q, name, food):
for i in range(10):
time.sleep(random.uniform(0.3, 0.8))
print('%s生产了一个%s%s' % (name, food, i))
q.put(food +str(i))
if __name__ == '__main__':
q = Queue()
c1 = Process(target=consumer, args=(q, 'L'))
c1