Created
May 22, 2019 07:17
-
-
Save clemaitre58/98ecdf861ac27041f85939e570e78c77 to your computer and use it in GitHub Desktop.
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 asyncio | |
| import random | |
| async def produce(queue, n): | |
| for x in range(1, n + 1): | |
| # produce an item | |
| print('producing {}/{}'.format(x, n)) | |
| # simulate i/o operation using sleep | |
| await asyncio.sleep(random.random()) | |
| item = str(x) | |
| # put the item in the queue | |
| await queue.put(item) | |
| # indicate the producer is done | |
| await queue.put(None) | |
| async def consume(queue): | |
| while True: | |
| # whttp://localhost:8888/notebooks/exception-sys-fichier-asyncio.ipynb#ait for an item from the producer | |
| item = await queue.get() | |
| if item is None: | |
| # the producer emits None to indicate that it is done | |
| break | |
| # process the item | |
| print('consuming item {}...'.format(item)) | |
| # simulate i/o operation using sleep | |
| await asyncio.sleep(random.random()) | |
| loop = asyncio.get_event_loop() | |
| queue = asyncio.Queue(loop=loop) | |
| producer_coro = produce(queue, 10) | |
| consumer_coro = consume(queue) | |
| loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro)) | |
| loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment