import threading
import time
def tt(t):
# 开启线程限制
with pool_sema:
print(t)
time.sleep(2)
if __name__ == '__main__':
# 并发的线程数设置
thread_nums = 2
pool_sema = threading.BoundedSemaphore(value=thread_nums)
threads = []
for i in range(1, 20):
th = threading.Thread(target=tt, args=(i,))
th.start()
threads.append(th)
for th in threads:
th.join()
python的threading模块限制线程并发数
最新推荐文章于 2024-08-30 15:05:50 发布
该博客演示了如何使用Python的threading模块和BoundedSemaphore来限制并发线程的数量。在main函数中,设定并发线程数为2,并创建19个线程,每个线程调用tt函数,该函数在获取到信号量后打印线程号并休眠2秒。通过这种方式,可以控制同时运行的线程不超过设定值,实现线程同步。
566





