Python多线程 Queue 模块常见用法
本文详细介绍Python标准库中Queue模块的用法,涵盖FIFO、LIFO及优先级队列。重点解析qsize、get、put等核心方法,并通过多线程同步示例演示如何利用队列实现线程间数据的安全交换与任务调度,确保并发环境下的数据一致性。
Queue模块介绍
Queue是Python内置的标准库,通常被称为队列。开发者可以直接通过import语句引入该模块。需要注意的是,在Python 2.x版本中,该模块的名称为Queue。在Python环境中,多个线程共享数据时,直接进行数据交换可能引发安全性和一致性问题。因此,当多线程需要交换数据时,引入队列机制可以完美解决这一问题,确保线程间数据交换的安全性和一致性。
Python的Queue模块提供了多种同步且线程安全的队列类,主要包括:FIFO(先进先出)队列Queue、LIFO(后进先出)队列LifoQueue,以及优先级队列PriorityQueue。
上述所有队列类均实现了锁原语,支持在多线程环境中直接使用,可用于实现线程间的同步操作。Queue模块中常用的方法包括:
- Queue.qsize():返回当前队列中的元素数量。 - Queue.empty():若队列为空则返回True,否则返回False。 - Queue.full():若队列已满则返回True,否则返回False;该状态与maxsize参数相关。 - Queue.get([block[, timeout]]):从队列中获取元素,支持设置阻塞等待时间timeout。 - Queue.get_nowait():等效于Queue.get(False),非阻塞获取。 - Queue.put(item):向队列写入元素,支持设置阻塞等待时间timeout。 - Queue.put_nowait(item):等效于Queue.put(item, False),非阻塞写入。 - Queue.task_done():在处理完一项任务后调用,向队列发送任务完成信号。 - Queue.join():阻塞直到队列为空,之后方可执行其他操作。
import threading
import time
def a():
print("a start\n")
for i in range(10):
time.sleep(0.1)
print("a finish\n")
def b():
print("b start\n")
print("b finish\n")
def main():
# t=threading.Thread(target=a,name="T")
t = threading.Thread(target=a)
t2=threading.Thread(target=b)
t.start()
t2.start()
# t2.join()
# t.join()
print("all done\n")
if __name__ == '__main__':
main()
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 ("开启线程:" + self.name)
process_data(self.name, self.q)
print ("退出线程:" + self.name)
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print ("%s processing %s" % (threadName, data))
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-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 ("退出主线程")
以上就是关于Python多线程中Queue模块的详细介绍。如需了解更多相关内容,建议查阅本站过往文章或继续浏览后续教程。感谢大家的支持!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









