Queue 线程安全队列
python内置queue 模块,用于线程安全管理,它提供了同步的、线程安全的队列类,包括FIFO, LIFO队列。这些队列都实现了锁原语,能在多线程中直接使用。可以使用队列来实现线程间的同步。
相关函数如下:
- Queue(maxsize):创建一个先进先出的队列
- qsize():返回队列的大小
- empty():判断队列是否为空
- full():判断队列是否满
- get():获取队列最后一个数据
- put():将数据放入队列
from queue import Queueq = Queue(4)for x in range(5):try:q.put(x, block=False)#block=false表示非阻塞,当队列满了再添加时会抛出异常, 默认情况下为阻塞except:break
print(q.qsize())if q.full():print('满了')for x in range(5):try:value = q.get(block=False)except:breakprint(value)if q.empty():print("空")print('完成')
一个例子:
import random
import threading
import time
from queue import Queuedef add_value(q):while True:q.put(random.randint(0, 10))time.sleep(1)def get_value(q):while True:print('获得到值:%d'%q.get())def main():q = Queue(10)th1 = threading.Thread(target=add_value, args=[q])th2 = threading.Thread(target=get_value, args=[q])th1.start()th2.start()if __name__ == '__main__':main()