Created
March 23, 2018 04:20
-
-
Save pipermerriam/8a71d6455c79a5e23d8ff63208b31e8d 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 | |
class Network: | |
input = asyncio.Queue() | |
outputs = [] | |
async def broadcast(network): | |
while True: | |
print('broadcast waiting for message') | |
message = await network.input.get() | |
print('broadcast got message: {0}'.format(message)) | |
print('broadcasting to {0} consumers'.format(len(network.outputs))) | |
for out in network.outputs: | |
await out.put(message) | |
await asyncio.sleep(0.1) | |
async def consumer(num, network): | |
my_queue = asyncio.Queue() | |
print('in consumer {0}'.format(num)) | |
network.outputs.append(my_queue) | |
while True: | |
print('in loop') | |
message = await my_queue.get() | |
await asyncio.sleep(0.1) | |
print('consumer {0} got message {1}'.format(num, message)) | |
async def producer(num, network): | |
asyncio.sleep(1) | |
for i in range(10): | |
print('producer {0} producing message {1}'.format(num, i)) | |
await network.input.put('message {0} from {1}'.format(i, num)) | |
await asyncio.sleep(random.random()) | |
loop = asyncio.get_event_loop() | |
asyncio.ensure_future(broadcast(Network)) | |
for i in range(2): | |
asyncio.ensure_future(consumer(i, Network)) | |
for i in range(3): | |
asyncio.ensure_future(producer(i, Network)) | |
loop.run_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment