Skip to content

Functions with "async def" will block the "def" functions #2488

Description

@xshone

I am builting web service with FastApi. Some functions have to be "await", so i wrote a function with "async def" named "get_list". But when the "get_list" functions was requested and executing, i request the "def" functions named "get_item" at the same time, the "def" function will be blocked by "time-consuming codes". I am confused.

So i want to know how to avoid the "async def" functions with time-consuming opertation inside blocking the "def" functions.

I use "for i in range(100000000)" to simulate some time-consuming opertation which will block the "def" functions.

# To simulate the time-consuming operation
for i in range(100000000):
    pass

All codes below:

import asyncio
import uvicorn

from fastapi import FastAPI

app = FastAPI()


@app.get('/get_item')
def get_item():
    # Will blocked by the 'get_list'
    return {"Key": "Value"}


@app.get('/get_list')
async def get_list():
    return await get_list_async()


async def get_list_async():

    # To simulate the time-consuming operation
    for i in range(100000000):
        pass

    print('start')
    await asyncio.sleep(10)
    print('end')

    # To simulate the time-consuming operation
    for i in range(100000000):
        pass

    ret_list = ['Item1', 'Item2', 'Item3']
    return ret_list


if __name__ == '__main__':
    uvicorn.run(app='main:app', host='0.0.0.0', port=8000, reload=True, debug=True)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions