😽

【Python】マルチプロセス + ノンブロッキングI/O処理

2021/02/24に公開

とりあえずコードを見てくれ。そして興味があれば調べてみるといい。

import asyncio
import time
import random
import concurrent.futures

# ランダム処理
def print_num(text):
    i = random.randrange(10)
    print (f"{text} - {i} sec - 開始")
    time.sleep(i)
    print (f"{text} 終了")

async def multi_process(loop,stock):
    executor = concurrent.futures.ProcessPoolExecutor()
    queue = asyncio.Queue()
    [queue.put_nowait(x) for x in stock]
    async def p(q):
        while not q.empty():
            i = await q.get()
            future = loop.run_in_executor(executor, print_num, i)
            await future

    # 8プロセスで処理
    tasks = [asyncio.create_task(p(queue)) for i in range(8)]
    return await asyncio.wait(tasks)

def main():
    stock = ["aaa","bbb","ccc","ddd","eee","fff","ggg","hhh"]
    loop = asyncio.new_event_loop()
    loop.run_until_complete(multi_process(loop,stock))

if __name__ == "__main__":  main()

これを使用したツール
Github
https://github.com/Trusted-Dream/Media-Downloader_for_LINE/blob/bb38ac5274413feca6273d929001618b6971d673/line/downloader.py#L81-L93

動作状況をYoutubeで
https://www.youtube.com/watch?v=NHd-SMjSdNE

Discussion