python多線程-Semaphore(信號對象)

Semaphore(value=1)

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,不然返回Truepython

release()
釋放信號,使計數器遞增1。當計數器爲零並有另外一個線程等待計數器大於零時,喚醒該線程。app

BoundedSemaphore(value=1)

實現有界信號對象。有界信號對象確保計數器不超過初始值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

相關文章
相關標籤/搜索