Python 的 Queue 模塊中提供了同步的、線程安全的隊列類,包括FIFO(先入先出)隊列Queue,LIFO(后入先出)隊列LifoQueue,和優(yōu)先級隊列 PriorityQueue。
這些隊列都實現(xiàn)了鎖原語,能夠在多線程中直接使用,可以使用隊列來實現(xiàn)線程間的同步。
模塊中的常用方法如下:
#!/usr/bin/python3 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 # 創(chuàng)建新線程 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 ("退出主線程")
知識點擴展:
問題
怎樣實現(xiàn)一個按優(yōu)先級排序的隊列? 并且在這個隊列上面每次 pop 操作總是返回優(yōu)先級最高的那個元素
解決方案
下面的類利用 heapq 模塊實現(xiàn)了一個簡單的優(yōu)先級隊列:
import heapq class PriorityQueue: def __init__(self): self._queue = [] self._index = 0 def push(self, item, priority): heapq.heappush(self._queue, (-priority, self._index, item)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1]
下面是它的使用方式:
>>> class Item: ... def __init__(self, name): ... self.name = name ... def __repr__(self): ... return 'Item({!r})'.format(self.name) ... >>> q = PriorityQueue() >>> q.push(Item('foo'), 1) >>> q.push(Item('bar'), 5) >>> q.push(Item('spam'), 4) >>> q.push(Item('grok'), 1) >>> q.pop() Item('bar') >>> q.pop() Item('spam') >>> q.pop() Item('foo') >>> q.pop() Item('grok') >>>
到此這篇關(guān)于python線程優(yōu)先級隊列知識點總結(jié)的文章就介紹到這了,更多相關(guān)python線程優(yōu)先級隊列有哪些內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:合肥 阜新 昭通 淘寶好評回訪 興安盟 隨州 信陽 濟源
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python線程優(yōu)先級隊列知識點總結(jié)》,本文關(guān)鍵詞 python,線程,優(yōu)先級,隊列,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。