Python进程间通信Queue

1.Queue使用方法:

  • Queue.qsize():返回当前队列包含的消息数量;
  • Queue.empty():如果队列为空,返回True,反之False ;
  • Queue.full():如果队列满了,返回True,反之False;
  • Queue.get():获取队列中的一条消息,然后将其从列队中移除,可传参超时时长。
  • Queue.get_nowait():相当Queue.get(False),取不到值时触发异常:Empty;
  • Queue.put():将一个值添加进数列,可传参超时时长。
  • Queue.put_nowait():相当于Queue.get(False),当队列满了时报错:Full

2.Queue使用实例:

实例1:

#!/usr/bin/env python3

import time
from multiprocessing import Process,Queue

q = Queue()  #创建列队,不传数字表示列队不限数量
for i in range(11):
    q.put(i)

def A():
    while 1:
        try:
            num = q.get_nowait()
            print('我是进程A,取出数字:%d'%num)
            time.sleep(1)
        except :
            break

def B():
    while 1:
        try:
            num = q.get_nowait()
            print('我是进程B,取出数字:%d'%num)
            time.sleep(1)
        except :
            break

p1 = Process(target = A)
p2 = Process(target = B)
p1.start()
p2.start()

此程序是在队列中加入10个数字,然后用2个进程来取出。

运行结果:

我是进程A,取出数字:0
我是进程B,取出数字:1
我是进程A,取出数字:2
我是进程B,取出数字:3
我是进程A,取出数字:4
我是进程B,取出数字:5
我是进程B,取出数字:6
我是进程A,取出数字:7
我是进程B,取出数字:8
我是进程A,取出数字:9
我是进程B,取出数字:10

 

实例2:

Process之间肯定是需要通信的,操作系统提供了很多机制来实现进程间的通信。Python的multiprocessing模块包装了底层的机制,提供了QueuePipes等多种方式来交换数据。

我们以Queue为例,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据:

from multiprocessing import Process, Queue
import os, time, random

# 写数据进程执行的代码:
def write(q):
    print('Process to write: %s' % os.getpid())
    for value in ['A', 'B', 'C']:
        print('Put %s to queue...' % value)
        q.put(value)
        time.sleep(random.random())

# 读数据进程执行的代码:
def read(q):
    print('Process to read: %s' % os.getpid())
    while True:
        value = q.get(True)
        print('Get %s from queue.' % value)

if __name__=='__main__':
    # 父进程创建Queue,并传给各个子进程:
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    # 启动子进程pw,写入:
    pw.start()
    # 启动子进程pr,读取:
    pr.start()
    # 等待pw结束:
    pw.join()
    # pr进程里是死循环,无法等待其结束,只能强行终止:
    pr.terminate()

运行结果:

Process to write: 50563
Put A to queue...
Process to read: 50564
Get A from queue.
Put B to queue...
Get B from queue.
Put C to queue...
Get C from queue.

 

3.使用进程池Pool时,Queue会出错,需要使用Manager.Queue:

#!/usr/bin/env python3

import time
from multiprocessing import Pool,Manager,Queue

q = Manager().Queue()
for i in range(11):
    q.put(i)

def A(i):
    num = q.get_nowait()
    print('我是进程%d,取出数字:%d'%(i,num))
    time.sleep(1)
            

pool = Pool(3)

for i in range(10):
    pool.apply_async(A,(i,))

pool.close()
pool.join()

运行结果:

我是进程1,取出数字:0
我是进程0,取出数字:1
我是进程2,取出数字:2
我是进程4,取出数字:3
我是进程3,取出数字:4
我是进程5,取出数字:5
我是进程6,取出数字:6
我是进程7,取出数字:7
我是进程8,取出数字:8
我是进程9,取出数字:9
  • 当把Manager().Queue()直接换成Queue(),可能会出现资源混乱,缺少进程。
posted @ 2018-11-26 10:06  Corey0606  阅读(429)  评论(0编辑  收藏  举报