Created
May 3, 2021 14:49
-
-
Save confiq/20e72912e4b825b7022feace284f1cf9 to your computer and use it in GitHub Desktop.
simple asyncio.Query usage from synchronous loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import signal | |
import time | |
import asyncio, random | |
# import uvloop | |
# asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) | |
async def consumer(queue): | |
while True: | |
revision = await queue.get() | |
if revision is False: | |
return | |
await asyncio.sleep(revision/10 * random.random() * 2) | |
queue.task_done() | |
print(f'done working on {revision}') | |
def main(): | |
loop = asyncio.get_event_loop() | |
queue = asyncio.Queue() | |
task = loop.create_task(consumer(queue)) | |
for run in range(1, 5): | |
print(f'produced {run}') | |
loop.run_until_complete(queue.put(run)) | |
time.sleep(.1) | |
print('---- done producing') | |
loop.run_until_complete(queue.put(False)) | |
# loop.run_until_complete(task) # runs forever | |
# loop.run_until_complete(asyncio.gather(task)) # runs forever | |
# loop.run_until_complete(queue.join()) # gives: Task was destroyed but it is pending! | |
loop.run_until_complete(task) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment