首页 > 编程笔记

Python queue模块简介

Python 的 queue 模块中提供了同步的、线程安全的队列类,包括 FIFO(先入先出)队列、LIFO(后入先出)队列和优先级队列。

这些队列能够在多线程中直接使用,可以使用队列来实现线程间的同步。

queue 模块中的常用方法如下:
【实例】线程优先级队列。
import queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q
    def run(self):
        print ("\n开启线程:" + self.name)
        process_data(self.name, self.q)
        print ("\n退出线程:" + self.name)
def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print ("%s 队列 %s " % (threadName, data))
        else:
            queueLock.release()
        time.sleep(1)
threadList = ["线程1", "线程2", "线程3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
# 创建新线程
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1
# 填充队列
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()
# 等待队列清空
while not workQueue.empty():
    pass
# 通知线程是时候退出
exitFlag = 1
# 等待所有线程完成
for t in threads:
    t.join()
print ("退出主线程")
保存并运行程序,输出结果如下:

开启线程:线程1
开启线程:线程2
开启线程:线程3
线程3 队列 One
线程1 队列 Two
线程2 队列 Three
线程3 队列 Four
线程1 队列 Five
退出线程:线程3
退出线程:线程2
退出线程:线程1
退出主线程

推荐阅读