python 归纳 (十三)_队列Queue在多线程中使用

# -*- coding: UTF-8 -*-
"""
多线程同时读队列

总结:
    1. 会阻塞
      if self._jobq.qsize() > 0  进入逻辑,此时被其他线程把数据取完了, 在data = self._jobq.get() 阻塞
    2. 需要学习锁使用

逻辑:
  * 主线程提前往队列写好所有数据
  * 子线程读取队列数据,没有就退出线程
"""
import Queue
import threading
import time
import random

q = Queue.Queue(0) # 无限大小的队列
NUM_WORKERS = 3    # 线程数量

class MyThread(threading.Thread):
    """从队列读取数据打印"""

    def __init__(self,queue,worktype):
       """
        :param queue:     队列
        :param worktype:  其他参数
       """
       threading.Thread.__init__(self)
       self._jobq = queue
       self._work_type = worktype

    def run(self):
       while True:
           if self._jobq.qsize() > 0:
                time.sleep(random.random() * 3)
                # 获取队列数据
                data = self._jobq.get()
                print "doing",data," worktype ",self._work_type
           else:
               print "%d,end" % self._work_type
               break

if __name__ == '__main__':
    print "begin...."
    # 往队列写数据
    for i in range(NUM_WORKERS * 2):
       q.put(i)

    print "job qsize:",q.qsize()

    # 启动线程
    for x in range(NUM_WORKERS):
       MyThread(q,x).start()

    print "end"

'''
Out:

begin....
job qsize: 6
end
doing 0  worktype  1
doing 1  worktype  0
doing 2  worktype  2
doing 3  worktype  1
doing 4  worktype  2
doing 5  worktype  0
0,end
阻塞 ......


'''

猜你喜欢

转载自www.cnblogs.com/sunzebo/p/9612339.html