强制CherryPy子线程
我想让cherrypy在自动重载的时候杀掉所有的子线程,而不是一直显示“等待子线程结束”。因为我的程序里有自己的线程,我不知道该怎么处理这个问题。CherryPy总是停在那一句话上,我不知道该怎么让“子线程”结束...
`
[05/Jan/2010:01:14:24] ENGINE HTTP Server cherrypy._cpwsgi_server.CPWSGIServer(('127.0.0.1', 8080)) shut down
[05/Jan/2010:01:14:24] ENGINE Stopped thread '_TimeoutMonitor'.
[05/Jan/2010:01:14:24] ENGINE Bus STOPPED
[05/Jan/2010:01:14:24] ENGINE Bus EXITING
[05/Jan/2010:01:14:24] ENGINE Bus EXITED
[05/Jan/2010:01:14:05] ENGINE Waiting for child threads to terminate...
`
它就是不继续运行。所以我想强制关闭子线程...
我知道这是因为我的应用程序使用了自己的线程,我猜cherrypy希望那些线程和CherryPy一起结束... 我能解决这个问题吗?
2 个回答
这个在快速入门中可以用
def stopit():
print 'stop handler invoked'
#...
stopit.priority = 10
cherrypy.engine.subscribe('stop', stopit)
为了支持它的生命周期,CherryPy 定义了一些常用的频道,这些频道会在不同的状态下被发布:
“start”:当总线处于“启动”状态时
“main”:CherryPy 的主循环会定期发布
“stop”:当总线处于“停止”状态时
“graceful”:当总线请求重新加载订阅者时
“exit”:当总线处于“退出”状态时
这些频道会由引擎自动发布。因此,注册任何需要对引擎状态变化做出反应的订阅者。
..
为了与总线进行交互,系统提供了以下简单的接口:
cherrypy.engine.publish(channel, *args):
channel 参数是一个字符串,用来标识消息应该发送到哪个频道
*args 是消息,可以包含任何有效的 Python 值或对象。
cherrypy.engine.subscribe(channel, callable):
channel 参数是一个字符串,用来标识可调用对象将要注册到哪个频道。
callable 是一个 Python 函数或方法,它的参数格式必须与将要发布的内容匹配。
你需要写一些代码来停止你的线程,并把它注册为一个“停止”事件的监听器:
from cherrypy.process import plugins
class MyFeature(plugins.SimplePlugin):
"""A feature that does something."""
def start(self):
self.bus.log("Starting my feature")
self.threads = mylib.start_new_threads()
def stop(self):
self.bus.log("Stopping my feature.")
for t in self.threads:
mylib.stop_thread(t)
t.join()
my_feature = MyFeature(cherrypy.engine)
my_feature.subscribe()
想了解更多细节,可以查看 http://www.cherrypy.org/wiki/BuiltinPlugins 和 http://www.cherrypy.org/wiki/CustomPlugins。