多线程
3种实现方式
- 直接使用Thread类创建
- 继承Thread类
- 使用concurrent.futures模块下的线程池–ThreadPoolExecutor
线程通信
- 共享全局变量
- 使用queue模块下的线程队列–Queue、PriorityQueue
线程同步
- Lock、RLock
- Event
- Condition–wait、notify
- Semaphore、BoundedSemaphore–acquire(计数器+1)、release(计数器-1),通过计数器控制线程数量
多进程
4种实现方式
- 直接使用Process类创建
- 继承Process类
- 使用concurrent.futures模块下的线程池–ProcessPoolExecutor
- 使用multiprocessing模块下的线程池–Pool
进程通信
- 使用multiprocessing模块下的进程队列–Queue(不能用于Pool线程池)
- 使用multiprocessing模块下Manager类实例中的进程队列–Manager().Queue
- 使用multiprocessing模块下的管道–Pipe(只适用于两个进程之间的通信)
- 使用multiprocessing模块下Manager类实例共享变量–Manager().dict、Manager.list等
ThreadPoolExecutor线程池和ProcessPoolExecutor进程池的使用
from concurrent.futures import ThreadPoolExecutor, Future, as_completed
def run_task(id):
print(id)
return 'Task:{}'.format(id)
executor = ThreadPoolExecutor(3) # 创建3线程的线程池
task = executor.submit(run_task, 1) # 提交一条执行任务到线程池
print(isinstance(task,Future)) # 返回的task为Future对象,会保存任务的状态和执行结果
tasks = [executor.submit(run_task, id) for id in range(2,5)] # 批量提交任务到线程池
tasks.append(task)
for future in as_completed(tasks):
result = future.result() # 线程池中的任务执行完成后会将返回结果保存在其对应的future对象中
print(result)
# 其它
task.cancel() # 取消某条还未执行得任务
from concurrent.futures import wait, FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED
done_tasks, not_done_tasks = wait(tasks, return_when=FIRST_COMPLETED) # wait函数在return条件成立时返回,返回(已完成任务集,未完成任务集)