- 互斥锁同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据 ,
- 比如酒店有5个房间,那最多只允许5个人开房,后面的人只能等里面有人出来了才能再进去。
#!/usr/bin/env python
# coding:utf-8
import threading
import time
def work(num, _semaphore):
_semaphore.acquire()
time.sleep(1)
print(f"run the thread:{num}")
_semaphore.release()
if __name__ == '__main__':
semaphore = threading.BoundedSemaphore(5)
for i in range(20):
t = threading.Thread(target=work, args=(f't-{i}', semaphore))
t.start()
while threading.active_count() != 1:
print(f'active_count: {threading.active_count()}')
else:
print('all threads done.')