Chinaunix首页 | 论坛 | 博客
  • 博客访问: 229774
  • 博文数量: 57
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 557
  • 用 户 组: 普通用户
  • 注册时间: 2015-10-01 18:05
文章分类

全部博文(57)

文章存档

2017年(57)

我的朋友

分类: Python/Ruby

2017-12-18 16:41:58

Python提供了Queue模块来专门实现消息队列

Queue对象

    Queue对象实现一个fifo队列(其他的还有lifo、priority队列,这里不再介绍)。queue只有maxsize一个构造参数,用来指定队列容量,指定为0的时候代表容量无限。主要有以下成员函数:

    Queue.qsize():返回消息队列的当前空间。返回的值不一定可靠。

    Queue.empty():判断消息队列是否为空,返回True或False。同样不可靠。

    Queue.full():类似上边,判断消息队列是否满

    Queue.put(item, block=True, timeout=None):往消息队列中存放消息。block可以控制是否阻塞,timeout指定阻塞时候的等待时间。如果不阻塞或者超时,会引起一个full exception。

    Queue.put_nowait(item):相当于put(item, False).

    Queue.get(block=True, timeout=None):获取一个消息,其他同put。

以下两个函数用来判断消息对应的任务是否完成。

    Queue.task_done():接受消息的线程通过调用这个函数来说明消息对应的任务已完成。

    Queue.join(): 实际上意味着等到队列为空,再执行别的操作


程序示例代码如下:
 

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author :Alvin.xie
  4. # @Time :2017-12-18 16:48
  5. # @file :4.py

  6. import random, threading, time
  7. from Queue import Queue


  8. # Producer thread
  9. class Producer(threading.Thread):
  10.     def __init__(self, t_name, queue):
  11.         threading.Thread.__init__(self, name=t_name)
  12.         self.data = queue

  13.     def run(self):
  14.         for i in range(10): # 随机产生10个数字 ,可以修改为任意大小
  15.             # randomnum=random.randint(1,99)
  16.             print "%s: %s is producing %d to the queue!" % (time.ctime(), self.getName(), i)
  17.             self.data.put(i) # 将数据依次存入队列
  18.             # time.sleep(1)
  19.         print "%s: %s finished!" % (time.ctime(), self.getName())


  20. # Consumer thread
  21. class Consumer_even(threading.Thread):
  22.     def __init__(self, t_name, queue):
  23.         threading.Thread.__init__(self, name=t_name)
  24.         self.data = queue

  25.     def run(self):
  26.         while 1:
  27.             try:
  28.                 val_even = self.data.get(1, 5) # get(self, block=True, timeout=None) ,1就是阻塞等待,5是超时5秒
  29.                 if val_even % 2 == 0:
  30.                     print "%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(), self.getName(), val_even)
  31.                     time.sleep(2)
  32.                 else:
  33.                     self.data.put(val_even)
  34.                     time.sleep(2)
  35.             except: # 等待输入,超过5秒 就报异常
  36.                 print "%s: %s finished!" % (time.ctime(), self.getName())
  37.                 break


  38. class Consumer_odd(threading.Thread):
  39.     def __init__(self, t_name, queue):
  40.         threading.Thread.__init__(self, name=t_name)
  41.         self.data = queue

  42.     def run(self):
  43.         while 1:
  44.             try:
  45.                 val_odd = self.data.get(1, 5)
  46.                 if val_odd % 2 != 0:
  47.                     print "%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(), self.getName(), val_odd)
  48.                     time.sleep(2)
  49.                 else:
  50.                     self.data.put(val_odd)
  51.                     time.sleep(2)
  52.             except:
  53.                 print "%s: %s finished!" % (time.ctime(), self.getName())
  54.                 break


  55. # Main thread
  56. def main():
  57.     queue = Queue()
  58.     producer = Producer('Pro.', queue)
  59.     consumer_even = Consumer_even('Con_even.', queue)
  60.     consumer_odd = Consumer_odd('Con_odd.', queue)
  61.     producer.start()
  62.     consumer_even.start()
  63.     consumer_odd.start()
  64.     producer.join()
  65.     consumer_even.join()
  66.     consumer_odd.join()
  67.     print 'All threads terminate!'


  68. if __name__ == '__main__':
  69.     main()
执行结果如下:
Mon Dec 18 16:49:04 2017: Pro. is producing 0 to the queue!
Mon Dec 18 16:49:04 2017: Pro. is producing 1 to the queue!
Mon Dec 18 16:49:04 2017: Pro. is producing 2 to the queue!
Mon Dec 18 16:49:04 2017: Pro. is producing 3 to the queue!
Mon Dec 18 16:49:04 2017: Con_even. is consuming. 0 in the queue is consumed!
Mon Dec 18 16:49:04 2017: Pro. is producing 4 to the queue!
Mon Dec 18 16:49:04 2017: Con_odd. is consuming. 1 in the queue is consumed!
Mon Dec 18 16:49:04 2017: Pro. is producing 5 to the queue!
Mon Dec 18 16:49:04 2017: Pro. is producing 6 to the queue!
Mon Dec 18 16:49:04 2017: Pro. is producing 7 to the queue!
Mon Dec 18 16:49:04 2017: Pro. is producing 8 to the queue!
Mon Dec 18 16:49:04 2017: Pro. is producing 9 to the queue!
Mon Dec 18 16:49:04 2017: Pro. finished!
Mon Dec 18 16:49:06 2017: Con_even. is consuming. 2 in the queue is consumed!
Mon Dec 18 16:49:06 2017: Con_odd. is consuming. 3 in the queue is consumed!
Mon Dec 18 16:49:08 2017: Con_even. is consuming. 4 in the queue is consumed!
Mon Dec 18 16:49:08 2017: Con_odd. is consuming. 5 in the queue is consumed!
Mon Dec 18 16:49:10 2017: Con_even. is consuming. 6 in the queue is consumed!
Mon Dec 18 16:49:10 2017: Con_odd. is consuming. 7 in the queue is consumed!
Mon Dec 18 16:49:12 2017: Con_even. is consuming. 8 in the queue is consumed!
Mon Dec 18 16:49:12 2017: Con_odd. is consuming. 9 in the queue is consumed!
Mon Dec 18 16:49:19 2017: Con_even. finished!
Mon Dec 18 16:49:19 2017: Con_odd. finished!
All threads terminate!


Process finished with exit code 0








阅读(1937) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~