import queue
import threading
import time
#线程思路:
#创建任务队列workQueue,和创建多条线程,然后将任务队列传入多线程中,
#在线程运行中,使用线程锁循环将任务读出,再执行任务,使用join函数等待所有线程完成任务。
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(2)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One-queue", "Two-queue", "Three-queue", "Four-queue", "Five-queue"]
#线程锁
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()
print("等待队列清空")
# 分配任务到每个线程,等待队列清空
while not workQueue.empty():
pass
# 所有任务分配完成,通知线程是时候退出,即通知线程已经没有任务了,可以退出了
exitFlag = 1
# 等待所有线程完成
for t in threads:
t.join()
print ("退出主线程")
python3 多线程与队列
最新推荐文章于 2022-06-20 19:49:48 发布
该博客介绍了一种使用Python实现多线程处理任务的方法,通过创建任务队列workQueue,并分配给多个线程。每个线程在运行时会循环读取并处理队列中的数据,直至队列清空。线程间通过线程锁queueLock进行同步,确保数据安全。在所有任务完成后,设置退出标志,等待所有线程完成工作,最后主线程退出。

8万+

被折叠的 条评论
为什么被折叠?



