Skip to content

Instantly share code, notes, and snippets.

@codecakes
Created November 17, 2021 21:31
Show Gist options
  • Save codecakes/6d7f44f0cfc60b85f4e10147ae7d9697 to your computer and use it in GitHub Desktop.
Save codecakes/6d7f44f0cfc60b85f4e10147ae7d9697 to your computer and use it in GitHub Desktop.
Context switching from one blocking statement to other and switching back to one until the other resumes.
import concurrent.futures as cf
import asyncio
from time import sleep
def two():
print('two')
sleep(4) # blocking
print('two again')
async def foo(loop: asyncio.AbstractEventLoop):
print('one')
with cf.ThreadPoolExecutor() as pool:
future = loop.run_in_executor(pool, two)
print('\none again') # switches context here
return future
loop = asyncio.get_event_loop()
asyncio.run(foo(loop))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment