Last active
April 21, 2021 20:15
-
-
Save pcakhilnadh/0161d72c366078e5cb8004a31e29015a to your computer and use it in GitHub Desktop.
Asynchronous Programming Sample code snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import time | |
global var | |
var=0 | |
def expensive_process(): | |
return 1 | |
async def some_async(): | |
print("some_async START") | |
global var | |
var = expensive_process() | |
await asyncio.sleep(5) | |
print("some_async COMPLETE") | |
async def some_function(): | |
print("some_function START") | |
global var | |
asyncio.create_task(some_async()) | |
try: | |
async def message_check(): | |
global var | |
if var==1: | |
return | |
await asyncio.wait_for(message_check(), timeout=3.0) | |
except asyncio.TimeoutError: | |
print('timeout!') | |
print(var) | |
print("some_function COMPLETE") | |
def main(name): | |
print(f'Hi, {name}') | |
asyncio.run(some_function()) | |
print(f'Hi, {name}') | |
if __name__ == '__main__': | |
main('PyCharm') | |
#Output | |
#some_async START is not completed but terminated once the check is met | |
/* | |
Hi, PyCharm | |
some_function START | |
some_async START | |
1 | |
some_function COMPLETE | |
Hi, PyCharm | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment