標籤:logs ref 線程 self href htm col 功能 阻塞
可以把Condiftion理解為一把進階的瑣,它提供了比Lock, RLock更進階的功能,允許我們能夠控制複雜的線程同步問題。threadiong.Condition在內部維護一個瑣對象(預設是RLock),可以在建立Condigtion對象的時候把瑣對象作為參數傳入。Condition也提供了acquire, release方法,其含義與瑣的acquire, release方法一致,其實它只是簡單的調用內部瑣對象的對應的方法而已。基於此同步原語, 我實現了一個基本簡單的安全執行緒的優先隊列:
import heapqimport threading# import timeclass Item: def __init__(self, name): self.name = name def __repr__(self): return ‘Item({!r})‘.format(self.name)class PriorityQueue: def __init__(self): self._queue = [] self._index = 0 self.mutex = threading.Lock() self.cond = threading.Condition() def push(self, item, priority): self.cond.acquire() heapq.heappush(self._queue, (-priority, self._index, item)) # 存入一個三元組, 預設構造的是小頂堆 self._index += 1 self.cond.notify() # 喚醒一個掛起的線程 self.cond.release() def pop(self): self.cond.acquire() if len(self._queue) == 0: # 當隊列中資料的數量為0 的時候, 阻塞線程, 要實現安全執行緒的容器, 其實不難, 瞭解相關同步原語的機制, 設計好程式執行時的邏輯順序(在哪些地方阻塞, 哪些地方喚醒) self.cond.wait() # wait方法釋放內部所佔用的鎖, 同時線程被掛起, 知道接收到通知或逾時, 當線程被喚醒並重新佔用鎖, 程式繼續執行下去 else: x = heapq.heappop(self._queue)[-1] # 逆序輸出 self.cond.release() return xdef test1(p, item, index): for i in range(3): p.push(Item(item), index)def test2(p): for i in range(3): print(p.pop())if __name__ == ‘__main__‘: p = PriorityQueue() t1 = threading.Thread(target=test1, args=(p, ‘foo‘, 1)) t3 = threading.Thread(target=test1, args=(p, ‘bar‘, 2)) t4 = threading.Thread(target=test1, args=(p, ‘Ryan‘, 28)) t2 = threading.Thread(target=test2, args=(p,)) t5 = threading.Thread(target=test2, args=(p,)) t6 = threading.Thread(target=test2, args=(p,)) t1.start() t2.start() t1.join() t2.join() t3.start() t5.start() t3.join() t5.join() t4.start() t6.start() t4.join() t6.join()
我還實現了一個基於event 安全執行緒的優先隊列,請看<基於condition 實現的安全執行緒的優先隊列(python實現)>
基於condition 實現的安全執行緒的優先隊列(python實現)