所以我在python中读过关于异步线程的这篇好文章.很难,最后一个与GIL有一些麻烦,线程没有看起来那么有效.
幸运的是,python包含了多处理功能,它不受此问题的影响.
我想了解如何以异步方式实现多处理队列(为每个进程打开管道),这样它就不会挂起正在运行的async webserver.
我已经阅读了这篇topic但是我并不是在寻找性能,而是在计算出一个挂起我的网络服务器的大计算.那些计算需要图片,所以他们可能有一个重要的i / o交换,但据我所知,这是由异步处理得很好的东西.
所有的计算方法彼此分开,因此它们并不意味着要混合.
我正在尝试在ws处理程序前构建它.
如果你暗示异端,请告诉我:)
解决方法:
在#python irc上的某个人在异步执行程序上暗示我之后,以及关于reddit的另一个答案之后,这是从一篇文章中重新获得的:
(2)使用ProcessPoolExecutor
“ProcessPoolExecutor类是一个Executor子类,它使用一个进程池来异步执行调用. ProcessPoolExecutor使用多处理模块,它允许它侧向执行全局解释器锁定,但也意味着只能执行和返回可选对象.“
import asyncio
from concurrent.futures import ProcessPoolExecutor
def cpu_heavy(num):
print('entering cpu_heavy', num)
import time
time.sleep(10)
print('leaving cpu_heavy', num)
return num
async def main(loop):
print('entering main')
executor = ProcessPoolExecutor(max_workers=3)
data = await asyncio.gather(*(loop.run_in_executor(executor, cpu_heavy, num)
for num in range(3)))
print('got result', data)
print('leaving main')
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
这来自reddit上的另一个好人;)
标签:python,asynchronous,multithreading
来源: https://codeday.me/bug/20190627/1306510.html