Python Forum
How can I prevent context switching when calling an async function?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I prevent context switching when calling an async function?
#1
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
Reply
#2
On the second question I found this answer: inspect.iscoroutine(object) and inspect.iscoroutinefunction(object)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Newbie question about switching between files - Python/Pycharm Busby222 3 543 Oct-15-2023, 03:16 PM
Last Post: deanhystad
Question Using SQLAlchemy, prevent SQLite3 table update by multiple program instances Calab 3 701 Aug-09-2023, 05:51 PM
Last Post: Calab
  calling external function with arguments Wimpy_Wellington 7 1,344 Jul-05-2023, 06:33 PM
Last Post: deanhystad
  queue for async function python telegram.ext noctious 0 1,511 Jun-11-2023, 02:58 PM
Last Post: noctious
  Calling a function (which accesses a library) from another file mouse9095 4 767 Jun-07-2023, 08:55 PM
Last Post: deanhystad
  with open context inside of a recursive function billykid999 1 549 May-23-2023, 02:37 AM
Last Post: deanhystad
  Context-sensitive delimiter ZZTurn 9 1,392 May-16-2023, 07:31 AM
Last Post: Gribouillis
  How does open context manager work? deanhystad 7 1,263 Nov-08-2022, 02:45 PM
Last Post: deanhystad
  Help Switching between keyboard/Mic input in my code Extra 1 1,044 Aug-28-2022, 10:16 PM
Last Post: deanhystad
Smile How we can prevent screen recording murad_ali 3 1,758 Jul-29-2022, 10:29 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020