Skip to content

Instantly share code, notes, and snippets.

@e-dreyer
Created July 25, 2023 07:53
Show Gist options
  • Save e-dreyer/82196b2781b3ebc9429c8bb6607651ff to your computer and use it in GitHub Desktop.
Save e-dreyer/82196b2781b3ebc9429c8bb6607651ff to your computer and use it in GitHub Desktop.
Python asyncio with blocking functions
import asyncio
import time
async def func1():
print('func1 starting')
await asyncio.sleep(3)
print('func1 ending')
return "func1"
async def func2():
print('func2 starting')
await asyncio.sleep(2)
print('func2 ending')
return "func2"
async def func3():
print('func3 starting')
await asyncio.sleep(1)
print('func3 ending')
return "func3"
def blocking_func1():
print('blocking_func1 starting')
time.sleep(3)
print('blocking_func1 ending')
return "blocking_func1"
def blocking_func2():
print('blocking_func2 starting')
time.sleep(2)
print('blocking_func2 ending')
return "blocking_func2"
def blocking_func3():
print('blocking_func3 starting')
time.sleep(1)
print('blocking_func3 ending')
return "blocking_func3"
async def main():
# Run the async functions
result1, result2, result3 = await asyncio.gather(func1(), func2(), func3())
print("Async function results:", result1, result2, result3)
# Run the blocking functions in a non-blocking manner
loop = asyncio.get_event_loop()
result4, result5, result6 = await asyncio.gather(
loop.run_in_executor(None, blocking_func1),
loop.run_in_executor(None, blocking_func2),
loop.run_in_executor(None, blocking_func3),
)
print("Blocking function results:", result4, result5, result6)
if __name__ == "__main__":
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment