并发执行
python并发处理任务
from concurrent.futures import ThreadPoolExecutor, as_completed
def task(n):
time.sleep(2)
print(f"处理任务 {n}")
return n ** 2
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(task, i) for i in range(10)]
for future in as_completed(futures):
result = future.result()
print(f"任务返回结果 {result}")
输出
![输出](https://i-blog.csdnimg.cn/blog_migrate/4f346dab36a2520a1440ff66ea2d6a1b.png)
异步处理
python异步执行任务
import threading
import time
def background_task(arg1, arg2):
print('开始暂停')
time.sleep(3)
print('暂停结束')
thread = threading.Thread(target=background_task, args=(1, 2))
thread.start()
print('执行完成')
输出
![输出](https://i-blog.csdnimg.cn/blog_migrate/75e92bd433c43175731e3c0b825a570d.png)