Skip to content

Instantly share code, notes, and snippets.

@johnsca
Last active June 27, 2017 20:31
Show Gist options
  • Save johnsca/77f8e3cec0476a2a8be10bc7c87085f9 to your computer and use it in GitHub Desktop.
Save johnsca/77f8e3cec0476a2a8be10bc7c87085f9 to your computer and use it in GitHub Desktop.
import asyncio
import threading
import time
def thread_func():
print('thread_func: start')
async def inner_async(loop):
print('inner_async: start')
await asyncio.sleep(1, loop=loop)
print('inner_async: finish')
time.sleep(2)
loop = asyncio.get_event_loop()
loop.run_until_complete(inner_async(loop))
print('thread_func: finish')
async def async_func(loop):
print('async_func: start')
await asyncio.sleep(1, loop=loop)
print('async_func: finish')
thread = threading.Thread(target=thread_func)
thread.start()
print('main thread getting event loop')
loop = asyncio.get_event_loop()
loop.run_until_complete(async_func(loop))
thread.join()
thread_func: start
main thread getting event loop
async_func: start
async_func: finish
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "examples/deploy.py", line 14, in thread_func
loop = asyncio.get_event_loop()
File "/usr/lib/python3.5/asyncio/events.py", line 632, in get_event_loop
return get_event_loop_policy().get_event_loop()
File "/usr/lib/python3.5/asyncio/events.py", line 578, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-1'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment