Pythonの非同期処理を行うためのモジュールであるasyncio
に含まれるasyncio.Queue
を利用して、簡単なキューのput/getプログラムを作成します。
asyncio.Queueの基本
まずは、asyncio.Queue
の基本的な使い方を見てみましょう。以下に、非同期関数としてキューにデータを投入する役割をする関数を producer
、キューからデータを取得して処理する役割をする関数を consumer
とした例を示します。
import asyncio
async def producer(q):
for i in range(15):
item = "task{0}".format(i)
await q.put(item)
print("producer: put", item)
await asyncio.sleep(1)
async def consumer(q):
while True:
while q.empty():
await asyncio.sleep(3)
items = []
for _ in range(q.qsize()):
item = await q.get()
items.append(item)
results = await asyncio.gather(*[foo(item) for item in items])
print("consumer: done -> {0}".format(results))
for _ in range(len(items)):
q.task_done()
async def foo(item):
await asyncio.sleep(5)
print("foo: finished -> {0}".format(item))
return item
async def main_wrapper():
q = asyncio.Queue()
asyncio.create_task(consumer(q))
await asyncio.create_task(producer(q))
await q.join()
print("Finish!!")
if __name__ == '__main__':
asyncio.run(main_wrapper())
このコードは、producer
が15個のタスクを順番にキューに投入し、consumer
がその時点でキューに存在するタスクを取得し、foo
関数に値を渡し並列に処理を実行するものです。
asyncio.Queueの活用
asyncio.Queue
は、非同期処理を行う際に非常に便利なツールです。特に、大量のタスクを効率的に処理する必要がある場合や、タスクの処理順序が問わない場合には、asyncio.Queue
の活用を検討してみてください。
以上、Pythonとasyncio.Queue
の活用について簡単に説明しました。この記事が、あなたのPythonプログラミングに役立つことを願っています。