python的queue模組中提供了同步的、執行緒安全的佇列類,包括fifo(先入先出)佇列queue,lifo(後入先出)佇列lifoqueue,和優先順序佇列priorityqueue。這些佇列都實現了鎖原語,能夠在多執行緒中直接使用。可以使用佇列來實現執行緒間的同步。
import threading
import time
from queue import queue
class producer(threading.thread):
def run(self):
global queue
count=0
while true:
for i in range(100):
if queue.qsize()>1000:
pass
else:
count=count+1
msg='produce'+str(count)
queue.put(msg)
print msg
time.sleep(1)
class consumer(threading.thread):
def run(self):
global queue
while true:
for i in range(3):
if queue.qsize()<100:
pass
else:
msg=self.name+'consume'+queue.get()
print msg
time.sleep(1)
queue=queue()
def test():
for i in range(500):
queue.put('init produce'+str(i))
for i in range(2):
p=producer()
p.start()
for i in range(5):
c=consumer()
c.start()
if __name__=='__main__':
test()
佇列同步器
1 abstractqueuedsynchronizer 頭節點 獲取同步狀態成功的節點 尾節點 執行緒無法獲取到同步狀態,而被構造成節點,加入到同步佇列。加入佇列必須保證執行緒安全 compareandsettail node expect,node update 2 獨佔式同步 1 獲取同步狀態...
CLH同步佇列
aqs內部維護著乙個fifo佇列,該佇列就是clh同步佇列。clh同步佇列是乙個fifo雙向佇列,aqs依賴它來完成同步狀態的管理,當前執行緒如果獲取同步狀態失敗時,aqs則會將當前執行緒已經等待狀態等資訊構造成乙個節點 node 並將其加入到clh同步佇列,同時會阻塞當前執行緒,當同步狀態釋放時,...
python多執行緒程式設計 6 佇列同步
前面介紹了互斥鎖和條件變數解決執行緒間的同步問題,並使用條件變數同步機制解決了生產者與消費者問題。讓我們考慮更複雜的一種場景 產品是各不相同的。這時只記錄乙個數量就不夠了,還需要記錄每個產品的細節。很容易想到需要用乙個容器將這些產品記錄下來。python的queue模組中提供了同步的 執行緒安全的佇...