与Flask中的全球单身人士(WSGI)合作时,我是否需要担心种族状况? [英] Working with a global singleton in Flask (WSGI), do I have to worry about race conditions?

查看:73
本文介绍了与Flask中的全球单身人士(WSGI)合作时,我是否需要担心种族状况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Flask的世界演示为:

The hello world demo for Flask is:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

如果我这样修改该怎么办?

What if I modified this like so:

from flask import Flask
app = Flask(__name__)

a = 1
b = 2
c = 3

@app.route("/")
def hello():
    a += 1
    b += a
    c += b
    return "Hello World!"

if __name__ == "__main__":
    app.run()

我了解WSGI应用程序可能具有多个线程. hello函数可以同时在多个线程上运行,然后我们就有了竞争条件.这样对吗?如果上面的代码不是线程安全的,我该怎么做才能使其成为线程安全的?

I understand WSGI application might have multiple threads. The hello function could be running on multiple threads at the same time, and then we'd have a race condition. Is this correct? If the above code is not thread safe, what can I do to make it thread safe?

避免全局变量是一种可能的解决方案,但是您可以始终避免全局变量吗?如果我想要类似python对象缓存的东西怎么办?

Avoiding globals is a possible solution, but can you always avoid globals? What if I want something like a python object cache?

推荐答案

此答案不正确,但由于已被标记为已接受,因此我无法删除.而是删除其内容以避免混淆.

这篇关于与Flask中的全球单身人士(WSGI)合作时,我是否需要担心种族状况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆