dmontagu / fastapi-utils

Reusable utilities for FastAPI
MIT License
1.89k stars 165 forks source link

question about race condition #255

Closed rmGFW closed 3 months ago

rmGFW commented 2 years ago

https://github.com/dmontagu/fastapi-utils/blob/af95ff4a8195caaa9edaa3dbd5b6eeb09691d9c7/fastapi_utils/session.py#L33

hi , if two thread call the cached_engine , and one stoped in line 39 then yeild , and another thread start running and the engine is still none ,then both these two thread will call get_new_engine ,but there must be an engine will be overwrite by another .

may this can happend ?

yuval9313 commented 3 months ago

It's not supposed to lead to race condition, See the purpose is to run these async and not multithreaded, which means the first to reach the line would be the first to store in the thread context that engine.

Which means that in multithreaded instance you'd want each thread to create its own engine rather then sharing the same one