041队列queue(重要,多线程使用)

内容:队列类型、方法、使用

###############
queue定义了3种信息列队模式类
Queue([maxsize]):FIFO列队模式
LifoQueue([maxsize]):LIFO列队模式,栈模式


#######方法
q.qsize():返回列队大小
q.full():如果列队满了返回True,否则False
q.empty():如果列队为空返回True,否则为False


队列特点:先进先出,里面有一个锁,保证多线程数据安全

import queue

q = queue.Queue(3)   # 里面设置放多少个数据

q.put('jinxing')
q.put('xming')
q.put('qqqq')
q.put('q', 0)        # 0位置的参数默认是1,1表示超过设置个数该线程阻塞,0表示超过设置个数会报错

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

print(q.get(0))    # 0表示没有会报错,默认表示阻塞
View Code

 

作用:可以不用使用同步,队列里面有一个锁

看下面例子:

 1 from random import randint
 2 import threading
 3 from time import sleep
 4 import queue
 5 
 6 class Production(threading.Thread):
 7     def run(self):
 8         while True:
 9             r = randint(0,100)
10             q.put(r)
11             print("生产出来%s号包子"%r)
12             sleep(1)
13 
14 class Proces(threading.Thread):
15     def run(self):
16         while True:
17             ret = q.get()
18             print('吃掉%s号包子'%ret)
19 
20 if __name__ == '__main__':
21     q = queue.Queue()
22     threads = [Production(),Production(),Production(),Proces()]
23     for t in threads:
24         t.start()
View Code

 

posted @ 2018-03-12 16:47  Alos403  阅读(217)  评论(0编辑  收藏  举报