import threading, time
def fun(n):
'''
测试函数,每条线程沉睡5秒
'''
with semaphore:
# lock.acquire()
print(n)
time.sleep(5)
# lock.release()
def split_list_average(l, n):
'''
将列表 l 均分成大小为 n 的若干个列表
'''
for a in range(0, len(l), n): yield(l[a:a+n])
# 设置线程最大并发数为12
semaphore = threading.Semaphore(12)
# 创建线程锁,防止输出混乱
lock = threading.Lock()
# 创建线程对象并存储到列表 thraed_list 中
thread_list = list(map(lambda x: threading.Thread(target=fun, args=(x,)), range(1000)))
# 将 thread_list 分割成长度为100的若干列表
split_list = split_list_average(thread_list, 100)
for threads in split_list:
# 线程开始
list(map(lambda t: t.start()==1, threads))
# 线程阻塞,使子线程运行完再运行主线程
list(map(lambda t: t.join()==1, threads))
注:此处线程存储列表原长度为1000,后分割成长度为100的若干列表,再让这些分割列表依次运行线程,是因为电脑根据配置有最大的线程创建数量,如果一次性创建的线程数量超过上限,则会报错:RuntimeError: can’t start new thread