day9-队列

一、队列类型

 1 import Queue
 2 
 3 # 1.先进先出
 4 q = Queue.Queue(maxsize=3)
 5 # 2.后进先出
 6 # q = Queue.LifoQueue(maxsize=3)
 7 
 8 q.put("d1")
 9 q.put("d2")
10 q.put("d3")
11 # 获取队列大小
12 print q.qsize()
13 print q.get()
14 print q.get()
15 print q.get()
16 
17 # 此时q为空队列,如果用q.get()会卡死
18 # q.get_nowait()不等待,空队列直接抛出异常
19 # print q.get_nowait()
20 # 设置超时时间,超时空队列会抛出异常
21 # print q.get(timeout=2)
22 
23 # 3.存储数据时可设置优先级
24 q = Queue.PriorityQueue(maxsize=3)
25 q.put((10, 'd1'))
26 q.put((-1, 'd2'))
27 q.put((5, 'd3'))
28 print q.get()
29 print q.get()
30 print q.get()

二、生产者消费者模型

import threading
import Queue
q = Queue.Queue()


def Producer(name):
    for i in range(1, 10):
        q.put("baozi%s" % i)
        print("%s produce baozi%s" % (name, i))
    print("waiting....")
    # 队列阻塞直至包子全部消费完毕
    q.join()
    print("all baozi has gone...")


def Consumer(name):
    while q.qsize() > 0:
        q.get()
        print("[%s] get baozi and eat it" % name)
        # 告知队列已消费一个包子
        q.task_done()


p = threading.Thread(target=Producer, args=("Nana", ))
p.start()

c = Consumer("Cici")

三、边生产边消费

import time
import random
import Queue
import threading
q = Queue.Queue()


def Producer(name):
    count = 0
    while count < 20:
        time.sleep(random.randrange(3))
        q.put(count)
        print('Producer %s has produced %s baozi..' % (name, count))
        count += 1


def Consumer(name):
  count = 0
  while count < 20:
    time.sleep(random.randrange(4))
    if not q.empty():
        data = q.get()
        print(data)
        print('\033[32;1mConsumer %s has eat %s baozi...\033[0m' % (name, data))
    else:
        print("-----no baozi anymore----")
    count += 1

p1 = threading.Thread(target=Producer, args=('A',))
c1 = threading.Thread(target=Consumer, args=('B',))
p1.start()
c1.start()

 

posted @ 2017-11-25 16:16  不知所以  阅读(125)  评论(0)    收藏  举报