python的threading模块限制线程并发数

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,python)