使用twisted无疑摆脱不了reactor模型,reactor做为twisted框架的核心,它是利用循环体来等待事件的发生,然后用来处理发生事件。对于twisted官方文档为:
The reactor is the Twisted event loop within Twisted, the loop which drives
applications using Twisted. The reactor provides APIs for networking,
threading, dispatching events, and more.
其图形化模式如下:
这个循环就是一个reactor反应堆,它启动后就等待事件的发生并进行处理,所以也称为事件循环。
1.reactor的启动
from twisted.internet import reactor
reactor.run()
启用reactor只需引入,并不要创建,然后调用run函数即可。这样图5的事件循环就一直处于运行状态。reactor是在主线程中运行,空转的reactor并不会消耗cpu资源。
2. hello twisted
def hello():
print 'Hello from the reactor loop!'
print 'Lately I feel like I\'m stuck in a rut.'
from twisted.internet import reactor
reactor.callWhenRunning(hello)
print 'start twisted study'
reactor.run()
输出结果
start twisted study
Hellofromthereactorloop!
LatelyIfeellikeI'mstuckinarut.
代码中需要说明的事情有
1. hello函数是通过callWhenRuning调用的
2.hello函数执行时在reactor启动之后,即run函数之后
3. 自定义的代码和twisted代码是在同一个线程中进行的
4. twisted代码执行时,自定义代码处于暂停状态
5.自定义代码执行时,twisted处于暂停状态
6.reactor事件循环会在回调函数执行完成后恢复执行。
reactor回调模式可以参考图 6
3. 退出twisted
def hello():
print 'Hello from the reactor loop!'
print 'Lately I feel like I\'m stuck in a rut.'
reactor.stop()
from twisted.internet import reactor
reactor.callWhenRunning(hello)
print 'start twisted study'
reactor.run()
hello函数添加了reactor.stop(),这样就停止了twisted的reactor.
閱讀更多 用數說話 的文章