gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:45:45 29 4
gpt4 key购买 nike

我在 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com