瓶装、gevent和线程:gevent只能从单个线程中使用

3
我有一个使用线程的Python瓶子应用程序。由于我正在使用monkey.patch,线程会阻塞应用程序执行(来自线程的对话框会阻塞瓶路由响应客户端,直到被解除)。在这里进行一些小型研究后,发现我应该使用monkey patch而不尝试修补Thread:
# Patch python's threads with greenlets
from gevent import monkey
monkey.patch_all(thread=False)

这不会阻止我编写的最小示例
但在使用线程、像threading.setEvent()这样的方法进行密集使用时,会引发以下错误:
C:\Users\IEUser\downloadloft-localserver>python mainserver.py
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Program Files\DownloadLoft\Python27\lib\threading.py", line 551, in _
_bootstrap_inner
self.run()
  File "C:\Program Files\DownloadLoft\Python27\lib\threading.py", line 753, in r
un
self.finished.wait(self.interval)
  File "C:\Program Files\DownloadLoft\Python27\lib\threading.py", line 403, in w
ait
self.__cond.wait(timeout)
  File "C:\Program Files\DownloadLoft\Python27\lib\threading.py", line 262, in w
ait
_sleep(delay)
  File "c:\users\admini~1\appdata\local\temp\easy_install-sch3hm\gevent-0.13.8-p
y2.7-win32.egg.tmp\gevent\hub.py", line 79, in sleep
switch_result = get_hub().switch()
  File "c:\users\admini~1\appdata\local\temp\easy_install-sch3hm\gevent-0.13.8-p
y2.7-win32.egg.tmp\gevent\hub.py", line 135, in get_hub
raise NotImplementedError('gevent is only usable from a single thread')
NotImplementedError: gevent is only usable from a single thread

Bottle v0.12-dev server starting up (using GeventSocketIOServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.

Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Program Files\DownloadLoft\Python27\lib\threading.py", line 551, in _
_bootstrap_inner
self.run()
  File "C:\Program Files\DownloadLoft\Python27\lib\threading.py", line 753, in r
un
self.finished.wait(self.interval)
  File "C:\Program Files\DownloadLoft\Python27\lib\threading.py", line 403, in w
ait
self.__cond.wait(timeout)
  File "C:\Program Files\DownloadLoft\Python27\lib\threading.py", line 262, in w
ait
_sleep(delay)
  File "c:\users\admini~1\appdata\local\temp\easy_install-sch3hm\gevent-0.13.8-p
y2.7-win32.egg.tmp\gevent\hub.py", line 79, in sleep
switch_result = get_hub().switch()
  File "c:\users\admini~1\appdata\local\temp\easy_install-sch3hm\gevent-0.13.8-p
y2.7-win32.egg.tmp\gevent\hub.py", line 135, in get_hub
raise NotImplementedError('gevent is only usable from a single thread')
NotImplementedError: gevent is only usable from a single thread

这是否是gevent.monkeypatch已知的问题?有什么想法吗?
1个回答

0

Bottle应用程序是线程化的,因此您不能在Bottle路由中调用的任何函数中使用gevent。

为了帮助您,我需要猜测您使用线程的原因。

如果是为了加速您的Bottle网站,只需使用cherrypy服务器:

pip install cherrypy 

(或者只需将cherrypy目录转储到当前目录中,它是一个纯Python服务器)

然后以这种方式运行您的瓶装应用程序:

bottle.run(server='cherrypy')

如果您想进行非阻塞调用(例如获取URL)而不会阻塞响应,那么手动实现很容易:

  • 创建一个队列对象(它是一个特殊的队列,可以在线程之间填充和弹出)。
  • 创建并运行一个线程,其中包含无限循环,不断从队列中弹出并执行操作。
  • 当您需要进行非阻塞调用时,请将操作推送到队列中并继续执行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接