Python Forum

Full Version: How can I prevent context switching when calling an async function?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
If I use async functions, then all the functions above the stack should also be async, and their call should be preceded by the await keyword. This example emulates modern programs with several architectural layers of the application:

async def func1():
    await asyncio.sleep(1)
    
async def func2():
    await func1()
    
async def func3():
    await func2()
    
async def func4():
    await func3()
    
async def func5():
    await func4()
When an execution thread meet 'await', it can switch to another coroutine, which requires resources for context switching. With a large number of competing corutes and different levels of abstraction, these overheads may begin to limit the performance of the entire system. But in the presented example it makes sense to switch the context only in one case, on line:
await asyncio.sleep(1)
How can I ban context switching for certain asynchronous functions?

And one more question:
how I can recognize async function?

async def f1():
    asyncio.sleep(1)
    return 34

def f2():
    return 42

MyList = []
MyList.append(f1)
MyList.append(f2)

async def my_func():
    for func in MyList:
        value = await func()
        print(value)
    
asyncio.run(my_func())
Error:
value = await func() TypeError: object int can't be used in 'await' expression
On the second question I found this answer: inspect.iscoroutine(object) and inspect.iscoroutinefunction(object)