在Google App Engine中使用Python 2.7的线程
我有一个应用程序,之前在 Python 2.5 的 GAE(Google App Engine)上运行时使用了线程。最近一个月,我把它更新到了 Python 2.7,但线程就不工作了。我在谷歌和这里搜索过,想看看在 GAE 上使用 Python 2.7 时线程是否有问题,但没有找到相关信息。
以下是代码:
def post(self):
bloqueo = thread.allocate_lock()
bloqueo.acquire()
thread.start_new_thread(self.principal,(bloqueo,))
def principal (self,bloqueo):
bloqueo.acquire()
当我运行这段代码时,它在 thread.start_new_thread(self.principal,(bloqueo,)) 这一行停止,并给出了以下错误:
Thread running after request. Creation traceback:
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/runtime.py", line 151, in HandleRequest
error)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 328, in HandleRequest
return WsgiRequest(environ, handler_name, url, post_data, error).Handle()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 266, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~applcation/8.374533192190096875/src/arc.py", line 1938, in post
thread.start_new_thread(self.principal,(bloqueo,))
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/runtime.py", line 81, in StartNewThread
return base_start_new_thread(Run, ())
你知道问题出在哪里吗?怎么解决呢?
谢谢你
1 个回答
4
在Python 2.5的运行环境下,App Engine从来不支持线程。
线程支持是在Python 2.7的时候才引入的。所以我不明白这段代码怎么可能在2.5的环境下运行。
可以查看文档了解更多信息。
https://developers.google.com/appengine/docs/python/python25/diff27
另外,我也不明白为什么你会在前端请求中需要使用线程,这其实是另一个问题。
如果我们看看你遇到的具体错误,它说“请求后线程仍在运行。创建追踪信息:”
这意味着你在请求处理完后还想继续运行线程。在App Engine中,你不能这样做。你必须等所有线程完成后再返回。在线程中进行主要工作会让事情变得复杂。如果你想在前端请求中实现一些并发,应该使用异步操作。你现在尝试的做法是行不通的,也不会提高性能。
此外,如果另一个实例同时处理相同的请求,使用锁也没有任何帮助。这就是事务的作用。
尽管你提供的信息很少,我真的觉得你应该完全放弃使用线程。