python多线程与多进程

多线程

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条件成立时返回,返回(已完成任务集,未完成任务集)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值