Skip to content

Instantly share code, notes, and snippets.

@lukleh
Created May 13, 2016 17:31
Show Gist options
  • Save lukleh/8d741dfb507c08fd4ba8c3101c2efebb to your computer and use it in GitHub Desktop.
Save lukleh/8d741dfb507c08fd4ba8c3101c2efebb to your computer and use it in GitHub Desktop.
import asyncio, random
import threading
import time
q = asyncio.Queue()
@asyncio.coroutine
def produce():
while True:
print("putting")
yield from q.put(random.random())
yield from asyncio.sleep(0.5 + random.random())
@asyncio.coroutine
def produce2():
print("putting")
yield from q.put(random.random())
@asyncio.coroutine
def consume():
while True:
print("consuming")
value = yield from q.get()
print("Consumed", value)
loop = asyncio.get_event_loop()
def loop_in_thread(loop):
asyncio.set_event_loop(loop)
loop.create_task(consume())
loop.run_forever()
print("over")
t = threading.Thread(target=loop_in_thread, args=(loop,))
t.start()
loop.call_soon_threadsafe(asyncio.async, produce2())
time.sleep(0.1)
loop.call_soon_threadsafe(asyncio.async, produce2())
time.sleep(0.1)
loop.call_soon_threadsafe(asyncio.async, produce2())
time.sleep(0.1)
loop.call_soon_threadsafe(asyncio.async, produce2())
time.sleep(0.1)
print("END")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment