python - 我需要在 Google App Engine 中使用线程同步工具吗?

标签 python google-app-engine app-engine-ndb

我在 Google App Engine 1.7.4 上使用 Python 2.7 运行时,在我的 app.yaml 中使用 threadsafe: true

我有以下代码:

@ndb.tasklet
def fn_a(container):
    ''' access datastore and mutate container '''

@ndb.tasklet
def fn_b(container):
    ''' access datastore and mutate container '''

@ndb.toplevel
def parallel_fn():
    shared_container = set()

    yield fn_a(shared_container), fn_b(shared_container)

fn_a()fn_b() 都访问和改变 shared_container 并在 parallel_fn() 中调用. shared_container 是一个标准库,因此不是线程安全的。

我是否应该将 shared_container 的 mutator/accessor 方法包​​装在适当的 threading 标准库锁中?

据我对 App Engine 的了解,尽管设置了 threadsafe: true,但每个实例都是单线程的。因此是否不需要使用 threading 锁对象?

初步测试表明不需要锁,只会增加额外的开销和死锁。似乎也不应该做以下事情

if object not in shared_container:
    yield any tasklet operation
    shared_container.add(object)

因为 shared_container 可能会在 yield 操作期间被另一行执行更新,从而呈现 不在 shared_container 语句中的对象可能无效。然而

if object not in shared_container:
    shared_container.add(object)
    yield any tasklet operation

绝对没问题。

最佳答案

您不需要添加锁定代码,因为微线程不在单独的线程中运行。在 tasklet docs. 中阅读相关信息

如果您设置 threadsafe: true,则 GAE 是多线程的。启动不同的线程来处理同一实例上的多个请求。通常这不是问题,因为您应该将请求处理程序设计为无论如何都能够跨各种服务器实例运行。

这并不适用于这个问题,但如果您真的测试过线程问题,请小心。我不确定,但我相信在 dev_appserver 和生产 GAE 服务器上运行的线程行为是不同的,所以一定要在两者上进行测试。

关于python - 我需要在 Google App Engine 中使用线程同步工具吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14029376/

相关文章:

python - 泛型类的类方法

java - "enter"的 JSP 字符串导致问题

python - GAE ndb.JsonProperty() 默认列表

python - NDB写入是如何计算的?

python - Pandas - 将 2 级索引字典映射到 DataFrame 列

python - 在 OpenCV 中使用 StereoBM 的错误视差图

python - 如何计算最后一分钟的运行平均流量

python - 如何有效地进行批量索引查找?

java - Appengine 本地数据存储中的事务行为不一致?

python - ndb.StringProperty 如何等于 python 字符串?