并发执行
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}")
输出

异步处理
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('执行完成')
输出
