天天看點

66 - 請解釋什麼是信号量,以及如何使用信号量

描述一下什麼是信号量,如何使用信号量,請舉例說明

  • 信号量;最古老的同步原語之一,是一個計數器,
  • 當資源釋放時,計數器就會遞增,當申請資源時,計數器就會遞減
from threading import BoundedSemaphore
MAX = 3

semaphore = BoundedSemaphore(MAX)
print(semaphore._value)

semaphore.acquire()
print(semaphore._value)

semaphore.acquire()
print(semaphore._value)
print(semaphore.acquire())

print(semaphore._value)

# 如果沒有資源可以申請(_value 的值是0), 再次調用acquire方法,會被阻塞
print(semaphore.acquire(False))
print(semaphore._value)

semaphore.release() # 第一次釋放資源
print(semaphore._value)

semaphore.release() # 第二次釋放資源
print(semaphore._value)

semaphore.release() # 第三次釋放資源
print(semaphore._value)

# 無資源被占用,抛出異常
# semaphore.release() # 第四次釋放資源
# print(semaphore._value)      
3
2
1
True
0
False
0
1
2
3