queue队列,以及生产者消费者模型

queue

队列!特点是有序的,跟list的区别,list调用元素,其实就是复制,还要用remove给删掉,麻烦,queue更加方便

 

生成队列的方法:

class queue.Queue(maxsize=0) #先入先出  #maxsize可以设定队列大小

 

class queue.LifoQueue(maxsize=0) #last in fisrt out  后进先出,例如卖东西,大家都喜欢新鲜的

 

class queue.PriorityQueue(maxsize=0) #存储数据时可设置优先级的队列

#PriorityQueue VIP!!
#例子
import queue
q=queue.PriorityQueue()

q.put((18,'qiangql'))
q.put((2,'egbert'))
q.put((39,'boboka'))

print(q.get( ))
print(q.get( ))
print(q.get( ))

#运行结果
(2, 'egbert')
(18, 'qiangql')
(39, 'boboka')

 

 

基本语法:

 

存数据

Queue.put()

 

取数据

Queue.get(block=Truetimeout=None)    #block 堵塞,默认是Ture,娶不到数据卡主,timeout等待时间,最多等多久

 

判断队列大小 #当前队列大小

Queue.qsize()

 

设置队列大小

Queue(maxsize=99)

 

验证队列是否为空,返回真,假

Queue.empty()

 

Queue.task_done() #还没看一会补充

Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete.

If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue).

Raises a ValueError if called more times than there were items placed in the queue.

 

生产者消费者模型

例子1:

import threading,time
import queue



def producer():
    count=1
    while True:
        q.put('骨头%s'%count)
        print('生产骨头%s'%count)
        count+=1
        time.sleep(0.5)

def consumer(name):
    while True:
        print("%s 取到%s" %(name, q.get()))
        time.sleep(1.5)


q = queue.Queue(maxsize=10)
p = threading.Thread(target=producer, )
p.start()

c1 = threading.Thread(target=consumer,args=('qianglq',))
c2 = threading.Thread(target=consumer,args=('buring',))
c1.start()
c2.start()

执行结果:

  生产骨头1
  qianglq 取到骨头1
  生产骨头2
  buring 取到骨头2
  生产骨头3
  生产骨头4
  qianglq 取到骨头3
  buring 取到骨头4
  生产骨头5
  生产骨头6
  生产骨头7
  qianglq 取到骨头5
  生产骨头8
  buring 取到骨头6
  生产骨头9
  生产骨头10

 
 

例子2

import threading
import queue


def producer():
    for i in range(10):
        q.put("骨头 %s" % i)

    print("开始等待所有的骨头被取走...")
    q.join()
    print("所有的骨头被取完了...")


def consumer(n):
    while q.qsize() > 0:
        print("%s 取到" % n, q.get())
        q.task_done()  # 告知这个任务执行完了


q = queue.Queue()

p = threading.Thread(target=producer, )
p.start()

c1 = consumer("43轮")

执行结果:
开始等待所有的骨头被取走...
43轮 取到 骨头 0
43轮 取到 骨头 1
43轮 取到 骨头 2
43轮 取到 骨头 3
43轮 取到 骨头 4
43轮 取到 骨头 5
43轮 取到 骨头 6
43轮 取到 骨头 7
43轮 取到 骨头 8
43轮 取到 骨头 9
所有的骨头被取完了...

 

posted @ 2018-06-28 22:19  人无远虑  阅读(168)  评论(0编辑  收藏  举报