异步多处理python

Paw*_*awy 6 python multithreading asynchronous

因此,我读了这篇有关python中的异步线程的不错的文章。艰难的是,最后一个在GIL上遇到了一些麻烦,线程并不像看起来那样有效。

幸运的是,python集成了Multiprocessing,旨在不受此麻烦的影响。

我想了解如何以异步方式实现多处理队列(每个进程都打开Pipe),这样它就不会挂起正在运行的异步webserver

我已经阅读了这个主题,但是我不是在寻找性能,而是整理出一个很大的计算量,这些计算量会挂在我的Web服务器上。这些计算需要图片,因此它们可能会进行大量的I / O交换,但是据我了解,异步可以很好地处理这些事情。

所有的calc都是彼此分开的,因此不要混在一起。

我正在尝试在ws处理程序之前构建它。

如果您对此表示异端,也请让我知道:)

Paw*_*awy 5

在某人对#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))
Run Code Online (Sandbox Code Playgroud)

这是来自reddit上另一个好人的;)