python基于标准库的多线程操作
from concurrent.futures import ThreadPoolExecutor
from time import sleep
import concurrent
def worker(num):
print(f"Working on {num}")
sleep(1) # 模拟耗时操作
print(f"Finished {num}")
def main():
with ThreadPoolExecutor(max_workers=5) as executor: # 创建一个有5个线程的线程池
futures = [executor.submit(worker, i) for i in range(10)] # 提交任务给线程池
for future in concurrent.futures.as_completed(futures): # 等待所有任务完成
result = future.result() # 尽管worker函数没有返回值,但这里可以捕获异常
if __name__ == "__main__":
main()