Gevent joinall阻塞错误

1 投票
1 回答
568 浏览
提问于 2025-04-18 16:02

关于这个应用程序的一些背景信息:

  1. 用户通过网络发送请求。
  2. 服务器需要处理这些网络请求(每个请求需要20秒才能完成)。
  3. 然后服务器将响应发送给用户。

我的做法是先用webpy和mod_wsgi来实现请求处理的并行化。如果我启动大约20个线程,但由于每个线程都需要20秒才能完成,所以请求级别的多线程效果不太明显。因此,我需要减少这20秒的时间,我通过创建绿色线程(greenlets)来实现这一点。大概是这样的:

文件 wordprocess_gevent.py

import gevent
urls = ('/'. A)
class A:
  output = {}
  def POST(self):
    #words is a list of words
    method A(words):

  def A(self, words):
    threads = []
    for word in words:
      i_thread = gevent.spawn(B, word)
      threads.append(i_thread)
    gevent.joinall(threads, timeout=2)

  def B(self, word):
    #Process word takes 20 seconds
    result = process(word)
    a[word] = result

application = web.application(urls, globals()).wsgifunc()

我使用下面的mod_wsgi-express来启动这段代码:

mod_wsgi-express start-server wordprocess_gevent.py --processes 5 --server-root wsgi_logs/ --with-wdb &

当同时收到多个POST请求时,我会遇到这个错误:

LoopExit: This operation would block forever

出现在这一行:

gevent.joinall(threads, timeout=2)

但是如果我只发送一个POST请求,我就能得到想要的结果。请问有人能帮我解决这个问题吗?

1 个回答

1

所以我通过完全去掉mod_wsgi这个东西解决了这个问题。即使只用一个进程,当有多个请求同时过来的时候,结果还是一样。

我加上了下面的代码,现在一切都运行得很好了 :)

if __name__ == "__main__":
  application = web.application(urls, globals()).wsgifunc()
  appserver = WSGIServer(('', 8000), application)
  appserver.serve_forever()

撰写回答