- 互斥锁同时只允许一个线程更改数据,而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.')
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。