4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで、非同期処理(コルーチン)と、同期処理(マルチプロセス)を併用する

Last updated at Posted at 2019-01-12

以下、cpuをたくさん使う処理を別プロセスとしてフォークし、pipeで通信。親は、asyncioでコルーチンで回る、ような例です。

import asyncio
import aiohttp.web
from multiprocessing import Process, Queue, Pipe
import time

async def websocket_handler(request):
    print('Websocket connection starting')
    ws = aiohttp.web.WebSocketResponse()
    await ws.prepare(request)
    print('Websocket connection ready')
  #親プロセスで子プロセスから受信
    print(parent.recv())
    parent.send('hello2')
  #非同期処理
    async for msg in ws:
        print(msg)
        if msg.type == aiohttp.WSMsgType.TEXT:
            print(msg.data)
            if msg.data == 'close':
                await ws.close()
            else:
                await ws.send_str('pong')
    print('Websocket connection closed')
    return ws

def f2(child):
    #重い同期的処理、例えば画像処理
    print('f2 start')
    child.send('hello')
    time.sleep(3)
    print(child.recv())

if __name__ == '__main__':
  #通信チャネルとしてパイプを準備しておいて、別プロセスをフォーク
    parent, child = Pipe()
    p = Process(target=f2, args=(child,))
    p.start()
  #非同期処理のメインループ起動
    loop = asyncio.get_event_loop()
    app = aiohttp.web.Application(loop=loop)
    app.router.add_route('GET', '/ws', websocket_handler)
    aiohttp.web.run_app(app, host='192.168.0.6', port=8080)
    p.join()
4
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?