Semaphore
對象內部管理一個計數器,該計數器由每一個acquire()
調用遞減,並由每一個release()
調用遞增。計數器永遠不會低於零,當acquire()
發現計數器爲零時,線程阻塞,等待其餘線程調用release()
。
Semaphore
對象支持上下文管理協議。
方法:
acquire(blocking=True, timeout=None)
獲取信號。
當blocking=True
時:若是調用時計數器大於零,則將其減1並當即返回。若是在調用時計數器爲零,則阻塞並等待,直到其餘線程調用release()
使其大於零。這是經過適當的互鎖來完成的,所以若是多個acquire()
被阻塞,release()
將只喚醒其中一個,這個過程會隨機選擇一個,所以不該該依賴阻塞線程的被喚醒順序。
返回值爲True
。
當blocking=False
時,不會阻塞。若是調用acquire()
時計數器爲零,則會當即返回False
.
若是設置了timeout
參數,它將阻塞最多timeout
秒。若是在該時間段內沒有獲取鎖,則返回False
,不然返回True
。python
release()
釋放信號,使計數器遞增1。當計數器爲零並有另外一個線程等待計數器大於零時,喚醒該線程。app
實現有界信號對象。有界信號對象確保計數器不超過初始值value
,不然拋出ValueError
。
大多數狀況下,該對象用於保護有限容量的資源。ui
栗子:線程
# -*- coding:utf-8 -*- import threading import time sem = threading.Semaphore(3) class DemoThread(threading.Thread): def run(self): print('{0} is waiting semaphore.'.format(self.name)) sem.acquire() print('{0} acquired semaphore({1}).'.format(self.name, time.ctime())) time.sleep(5) print('{0} release semaphore.'.format(self.name)) sem.release() if __name__ == '__main__': threads = [] for i in range(4): threads.append(DemoThread(name='Thread-' + str(i))) for t in threads: t.start() for t in threads: t.join()
運行結果:code
Thread-0 is waiting semaphore. Thread-0 acquired semaphore(Thu Oct 25 20:33:18 2018). Thread-1 is waiting semaphore. Thread-1 acquired semaphore(Thu Oct 25 20:33:18 2018). Thread-2 is waiting semaphore. Thread-2 acquired semaphore(Thu Oct 25 20:33:18 2018). Thread-3 is waiting semaphore. Thread-0 release semaphore. Thread-3 acquired semaphore(Thu Oct 25 20:33:23 2018). Thread-1 release semaphore. Thread-2 release semaphore. Thread-3 release semaphore.
能夠看到Thread-3
是在Thread-0
釋放後纔得到信號對象。orm