Skip to main content
 首页 » 编程设计

python之flask 顶部的 unicorn (临界区)

2025年05月04日12lidabo

当我将 gunicorn 放在具有如下方法的 Flask 服务前面时:

@app.route('/testr/', methods=['POST']) 
def test(): 
  atomic_section_here 

据我了解,我可以创建多个 worker (比如说 5 个)。这是否意味着我得到 5 个进程,每个进程都有自己的解释器?还是我使用 multiprocessing 获得一个解释器生成的 5 个进程?

如果我希望临界区是原子的,我可以只在这个文件的顶层初始化一个锁并在临界区内获取它吗?

请您参考如下方法:

您从 1 个解释器中通过 multiprocessing 生成了 5 个进程。您可以在路由中使用 mutltiprocessing.Lock().aquire 并在 gunicorn.conf 中使用 preload_app = True 在工作人员之间共享锁。

Here is some reading about the design of Gunicorn, including the workers.

Here is a relevant question and answer about sharing the lock.