How does an asynchronous method behave when executing a synchronous Python method?

Asked

Viewed 89 times

1

In Python an asynchronous method is able to run in parallel, but if within it I have a "normal" function, it will also be run asynchronously or from that moment the execution will be "locked" and other functions cannot be executed "at the same time"?

def funcao_normal():
    # algum código aki...

async def funcao_assincrona():
    # algum código aki...
    funcao_normal()
    
await funcao_assincrona()
  • 1

    Is aware of the concept of choirs?

  • No, in vdd I just got into this asynchronous business, but now I know the name I have to look for (corotinas right?) Obg @Woss

1 answer

2


When you call a synchronous code from an asynchronous function the Event loop will be locked until the synchronous function returns. That is, if it is a non-blocking call (e.g. a function that only formats strings) there will be no problem. However, if it is a blocking call as access to a database, the Event loop may be stuck longer than expected giving other coroutines no chance to rotate.

The ideal is not to make blocking synchronous calls from asynchronous code, but if necessary, the correct way is to create an execute and put the synchronous function to run within it:

async def async_func():
    executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
    loop = asyncio.get_event_loop()
    result = await loop.run_in_executor(executor, sync_function, *args_for_sync_func)

Thus, the synchronous function will run on the Event loop current.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.