进程
一个正在运行的程序进程间内存不共享 通过进程间通信等传递信息线程
被包含在进程之中 独立执行相同程序运算调度的最小单位 宏观并行 微观分时切换串行共享同一份全局内存区域创建线程比创建进程通常要快10倍甚至更多线程/进程?池
一种管理工具(方法/思想)尽可能减少创建和销毁线程的次数 从而减少时间和资源消耗池化思想
复用资源 减少创建和释放的资源消耗对象池、连接池、内存池、线程池Python?中?线程?Thread?/?进程?Process?的使用最常用的两种方式ThreadPoolExecutor
ProcessPoolExecutor
使用“池”完成一组同类型任务
executor.map?会保持顺序
multiprocessing.Process
新建进程启动任意任务
例子 ThreadPoolExecutorfrom?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
对于?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?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
?
本文为大家介绍了在数据科学和机器学习中所需要的基本数学技能,并且分类给出了...
为了能更好地适应每一个时代的机遇与挑战,企业的制度需不断更新迭代。那么时至...
了解 Lua 如何处理数据的读写。 有些数据是临时的,存储在 RAM 中,只有在应用运...
服务器租用 哪里便宜?市场上提供服务器租用的厂商有很多,目前比较知名的有阿里...
撰稿 PolarDB新型存储引擎团队 历史数据归档的问题 大部分业务数据的读写特征 都...
?又到一年毕业季,即将开启(实习及正式)职场生涯的同学们会有不少疑惑。比如,...
是什么让中小企业拥抱了云计算? 对中小企业来说 云服务什么最重要 中小企业上云...
我们都知道开发过程中应该编写单元测试,实际上我们中的许多人都这样做。对于生...
报告综述 SaaS 从何而来,为何而生? 云计算概念兴起的背后是 IT 界从上世纪 60 ...
vip域名 在哪里可以注册? .vip域名 可以直接在 TOP云 平台注册,注册前先查询想...