python

来源:互联网 发布:tcp 长连接 java 框架 编辑:程序博客网 时间:2024/06/13 21:17

进程间通信-Queue

Process之间有时需要通信,操作系统提供了很多机制来实现进程间的通信。

1. Queue的使用

可以使用multiprocessing模块的Queue实现多进程之间的数据传递,Queue本身是一个消息列队程序,首先用一个小实例来演示下Queue的工作原理:
代码如下:

#coding=utf-8from multiprocessing import Queue#初始化一个Queue对象,最多可接收三条put消息q = Queue(3)q.put('消息1')q.put('消息2')print(q.full())#Falseq.put('消息3')print(q.full())#True#因为消息列队已满下面的try都会抛出异常,第一个try会等待2秒后再抛出异常,第二个Try会立刻抛出异常try:    q.put('消息4', True, 2)except:    print('消息队列已满,现有消息数量:%s'%q.qsize())try:    q.put_nowait('消息4')#等同于q.put('消息4', False)except:    print('消息队列已满,现有消息数量:%s'%q.qsize())#推荐的方式,先判断消息列队是否已满,再写入if not q.full():    q.put_nowait('消息4')#读取消息时,先判断消息列队是否为空,再读取if not q.empty():    for i in range(q.qsize()):        print(q.get_nowait())

运行结果:

FalseTrue消息队列已满,现有消息数量:3消息队列已满,现有消息数量:3消息1消息2消息3

说明

初始化Queue()对象时(例如:q=Queue()),若括号中没有指定最大可接收的消息数量,或数量为负值,那么就代表可接受的消息数量没有上限(直到内存的尽头);
Queue.qsize():返回当前队列包含的消息数量;
Queue.empty():如果队列为空,返回True,反之False ;
Queue.full():如果队列满了,返回True,反之False;
Queue.get([block[, timeout]]):获取队列中的一条消息,然后将其从列队中移除,block默认值为True;
1)如果block使用默认值,且没有设置timeout(单位秒),消息列队如果为空,此时程序将被阻塞(停在读取状态),直到从消息列队读到消息为止,如果设置了timeout,则会等待timeout秒,若还没读取到任何消息,则抛出”Queue.Empty”异常;
2)如果block值为False,消息列队如果为空,则会立刻抛出”Queue.Empty”异常;
Queue.get_nowait():相当Queue.get(False);
Queue.put(item,[block[, timeout]]):将item消息写入队列,block默认值为True;

1)如果block使用默认值,且没有设置timeout(单位秒),消息列队如果已经没有空间可写入,此时程序将被阻塞(停在写⼊状态),直到从消息列队腾出空间为止。如果设置了timeout,则会等待timeout秒,若还没空间,则抛出”Queue.Full”异常;
2)如果block值为False,消息列队如果没有空间可写入则会立刻抛
出”Queue.Full”异常;
Queue.put_nowait(item):相当Queue.put(item, False);

2. Queue实例

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

#coding=utf-8from multiprocessing import Queue, Processimport time, random, os#写数据进程执行的代码def write(q):    l1 = ['A','B','C']    for value in l1:        print('put %s to queue...'%value)        q.put(value)        time.sleep(random.random())#读数据执行的代码def read(q):    while True:        if not q.empty():            value = q.get(True)            print('get %s from queue...' % value)            time.sleep(random.random())        else:            breakif __name__ == "__main__":    #父进程创建Queue,并传给各个子进程    q = Queue()    qw = Process(target=write, args=(q,))    qr = Process(target=read, args=(q,))    #启动子进程qw写入    qw.start()    qw.join()    # 启动子进程qr写入    qr.start()    qr.join()    # qr进程是死循环,无法等待其结束,只能强行终止:    print('所有数据都已经写入并读取完毕')

运行结果:

put A to queue...put B to queue...put C to queue...get A from queue...get B from queue...get C from queue...所有数据都已经写入并读取完毕

3. 进程池中的Queue

如果要使用Pool创建进程,就需要使用multiprocessing.Manager()中的
Queue(),而不是multiprocessing.Queue(),否则会得到一条如下的错误信息:
RuntimeError: Queue objects should only be shared between processes
through inheritance.
下面的实例演示了进程池中的进程如何通信:
代码如下:

#coding=utf-8from multiprocessing import Manager, Poolimport time, random, osdef writer(q):    print('writer启动%s,父进程为%s'%(os.getpid(),os.getppid()))    l1 = ['a','b','c','d','e']    for value in l1:        q.put(value)def reader(q):    print('reader启动%s,父进程为%s'%(os.getpid(),os.getppid()))    for i in range(q.qsize()):        print('reader从Queue获取到消息:%s'%q.get(True))if __name__ == "__main__":    print('父进程%s启动...'%os.getpid())    q = Manager().Queue() #使用Manager中的Queue来初始化    po = Pool()    # 使用阻塞模式创建进程,这样就不需要在reader中使用死循环了,可以让writer完全执行完成后,再用reader去读取    po.apply(writer, (q,))    po.apply(reader, (q,))    po.close()    po.join()    print('%s结束'%os.getpid())

运行结果:

父进程7415启动...writer启动7421,父进程为7415reader启动7422, 父进程为7415reader从Queue获取到消息:areader从Queue获取到消息:breader从Queue获取到消息:creader从Queue获取到消息:dreader从Queue获取到消息:e7415结束
原创粉丝点击