# Author : Xuefeng
import threading, time
# Semahpore = threading.Semaphore()
def run(n):
# 启动线程程序
Semahpore.acquire()
time.sleep(1)
print("------ Run the %d thread------\n" % n)
Semahpore.release()
if __name__ == "__main__":
Semahpore = threading.BoundedSemaphore(5) # The amount of thread can't over 5 num at the same time
for i in range(22):
t = threading.Thread(target=run, args=(i,))
t.start()
while threading.active_count() != 1:
pass
else:
print("-------All thread run over--------")
Python_信号量控制同时运行几个线程
最新推荐文章于 2024-01-29 10:18:41 发布
本文探讨了Python中使用Semaphore进行线程同步的方法,通过限制同时运行的线程数量,确保资源合理分配,避免资源竞争,提高程序稳定性。
358

被折叠的 条评论
为什么被折叠?



