Skip to content

Instantly share code, notes, and snippets.

@nakamuray
Created July 1, 2016 00:57
Show Gist options
  • Save nakamuray/bc46db9f5045a74ce847590afb5fa3eb to your computer and use it in GitHub Desktop.
Save nakamuray/bc46db9f5045a74ce847590afb5fa3eb to your computer and use it in GitHub Desktop.
import threading
from asyncio_extras.threads import threadpool
async def main():
print('main:', threading.current_thread())
for _ in range(4):
async with threadpool():
import time
print('within threadpool:', threading.current_thread())
time.sleep(1)
print('within threadpool:', threading.current_thread(), 'done')
print('main:', threading.current_thread(), 'done')
if __name__ == '__main__':
import asyncio
loop = asyncio.get_event_loop()
#loop.run_until_complete(main())
loop.run_until_complete(asyncio.wait([main(), main()]))
@nakamuray
Copy link
Author

$ python threadpooltest.py
main: <_MainThread(MainThread, started 139720800528128)>
main: <_MainThread(MainThread, started 139720800528128)>
within threadpool: <Thread(Thread-1, started daemon 139720720750336)>
within threadpool: <Thread(Thread-1, started daemon 139720720750336)> done
within threadpool: <Thread(Thread-2, started daemon 139720712357632)>
within threadpool: <Thread(Thread-2, started daemon 139720712357632)> done
within threadpool: <Thread(Thread-1, started daemon 139720720750336)>
within threadpool: <Thread(Thread-1, started daemon 139720720750336)> done
within threadpool: <Thread(Thread-5, started daemon 139720687179520)>
within threadpool: <Thread(Thread-5, started daemon 139720687179520)> done
main: <_MainThread(MainThread, started 139720800528128)> done
Task exception was never retrieved
future: <Task finished coro=<main() done, defined at threadpooltest.py:6> exception=ValueError('coroutine already executing',)>
Traceback (most recent call last):
  File "/usr/x86_64-pc-linux-gnu/lib/python3.5/asyncio/tasks.py", line 241, in _step
    result = coro.throw(exc)
  File "threadpooltest.py", line 10, in main
    async with threadpool():
  File "/home/nakamuray/virtualenvs/sandbox35/lib/python3.5/site-packages/asyncio_extras/threads.py", line 46, in __await__
    yield future
  File "/usr/x86_64-pc-linux-gnu/lib/python3.5/asyncio/tasks.py", line 290, in _wakeup
    future.result()
  File "/usr/x86_64-pc-linux-gnu/lib/python3.5/asyncio/futures.py", line 274, in result
    raise self._exception
  File "/usr/x86_64-pc-linux-gnu/lib/python3.5/concurrent/futures/thread.py", line 55, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/nakamuray/virtualenvs/sandbox35/lib/python3.5/site-packages/asyncio_extras/threads.py", line 28, in exec_when_ready
    coro.send(None)
ValueError: coroutine already executing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment