Python 中的多线程优先级队列

pythonserver side programmingprogramming更新于 2025/5/7 11:56:17

Queue 模块允许您创建一个可以容纳特定数量项目的新队列对象。有以下方法可以控制队列 −

  • get() − get() 从队列中删除并返回一个项目。
  • put() − put 将项目添加到队列。
  • qsize() − qsize() 返回当前队列中的项目数。
  • empty() − 如果队列为空,empty() 返回 True;否则,返回 False。
  • full() − 如果队列已满,full() 返回 True;否则,为 False。

示例

#!/usr/bin/python
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 "Starting " + self.name
      process_data(self.name, self.q)
      print "Exiting " + 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 inthreads:
   t.join()
print "Exiting Main Thread"

执行上述代码时,会产生以下结果−

Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread

相关文章


有用资源