当前位置:主页 > 查看内容

在 Python 中使用 多线程 Multithreading, 多进程 Multiprocessi

发布时间:2021-04-26 00:00| 位朋友查看

简介:线程?Thread?/?进程?Process 进程 一个正在运行的程序进程间内存不共享 通过进程间通信等传递信息 线程 被包含在进程之中 独立执行相同程序运算调度的最小单位 宏观并行 微观分时切换串行共享同一份全局内存区域创建线程比创建进程通常要快10倍甚至更多 线程……
线程?Thread?/?进程?Process

进程

一个正在运行的程序进程间内存不共享 通过进程间通信等传递信息

线程

被包含在进程之中 独立执行相同程序运算调度的最小单位 宏观并行 微观分时切换串行共享同一份全局内存区域创建线程比创建进程通常要快10倍甚至更多

线程/进程?池

一种管理工具(方法/思想)尽可能减少创建和销毁线程的次数 从而减少时间和资源消耗

池化思想

复用资源 减少创建和释放的资源消耗对象池、连接池、内存池、线程池

Python?中?线程?Thread?/?进程?Process?的使用最常用的两种方式

ThreadPoolExecutor

ProcessPoolExecutor

使用“池”完成一组同类型任务

executor.map?会保持顺序

multiprocessing.Process

新建进程启动任意任务

例子 ThreadPoolExecutor
from?concurrent.futures?import?ThreadPoolExecutor
def?main():
????with?ThreadPoolExecutor()?as?executor:
????????executor.map(download,?links,?timeout 30)
ProcessPoolExecutor
from?concurrent.futures?import?ProcessPoolExecutor
def?main():
????with?ProcessPoolExecutor?as?executor:
????????executor.map(is_prime,?PRIMES)

具体?API?参考 concurrent.futures?—?Launching?parallel?tasks?—?Python?3.9.4?documentation

Process?
from?multiprocessing?import?Process
def?f(name):
????print( hello ,?name)
if?__name__? ? __main__ :
????p? ?Process(target f,?args ( bob ,))
????p.start()
????p.join()

具体?API?参考 multiprocessing?—?Process-based?parallelism?—?Python?3.9.4?documentation

Multithreading?vs?Multiprocessing?

IO?bound

multithreading?(less?overhead),?multiprocessing?

CPU?bound

multiprocessing

multiple?machines

RQ

对于?IO?密集型的任务 使用线程和进程均可 使用线程可以减少资源消耗

对于?CPU?密集型的任务 使用进程

优化

使用全局变量

或?multiprocessing.Queue

Don t?pickle?the?input,?This?will?save?a?lot?of?communication?overhead,?especially?if?the?output?is?small?compared?to?the?input

使用?chunk

ProcessPoolExecutor.map(chunksize? x)

对于大量小计算量任务 使用?chunk?充分利用?Process?资源 减少?overhead

常见问题

死锁

the?function?needs?to?be?defined?at?the?top-level,?nested?functions?won t?be?importable?by?the?child?and?already?trying?to?pickle?them?raises?an?exception

Reference

线程池源码浅析?(Java)

线程概念 Java?ThreadPoolExecutor

Don t?pickle?the?input?(stackoverflow)

?

https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing

官网文档

https://docs.python.org/3/library/threading.html

官网文档

Python?Multithreading?and?Multiprocessing?Tutorial

操作系统导论

?


本文转自网络,原文链接:https://developer.aliyun.com/article/783801
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:6 张图带你彻底搞懂分布式事务 XA 模式 下一篇:没有了

推荐图文


随机推荐