您的位置:首页 > 其它

twisted 线程里的几个函数

2013-05-14 16:08 176 查看
twisted里是通过回调机制来实现类似于多线程,意思是防止程序的运行由于等待某项任务的完成而陷入阻塞停滞,提高整体运行的效率。

from twisted.internet import reactor

1. reactor.callFromThread

Method callFromThread:

Cause a function to be executed by the reactor thread.

Use this method when you want to run a function in the reactor's thread from another thread. Calling callFromThread should wake up the main thread (where reactor.run() is executing) and run the given callable in that thread.

If you're writing a multi-threaded application the callable may need to be thread safe, but this method doesn't require it as such. If you want to call a function in the next mainloop iteration, but you're in the same thread, use callLater with
a delay of 0.

此方法是本身是mainloop的线程,用reactor.stop()可以终止它。也可以reactor.callFromThread(reactor.stop)来终止它。但是这个方法会阻塞到主循环。

#coding=utf-8

from twisted.internet import reactor

import time

def tt(i,j):

while 1:

print i,'---------------',j

time.sleep(1)

reactor.callFromThread(tt,1,1)

reactor.callFromThread(tt,4,2)

上面代码运行的结果是无限的打印1-------------------1,这个说明了主循环被阻塞住。

2. reactor.callInThread

Method callInThread:

Run the callable object in a separate thread.

此方法是创建独立的线程,用reactor stop方法无法停止它。这里涉及到一个线程池的概念

reactor.suggestThreadPoolSize(15)来设置线程池的大小,默认是最小是5,最大是10.如果在默认情况下

3. from twisted.internet import threads

threads.deferToThread(function),和callInThread一样,区别只是 deferToThread 可以返回一个deferred对象,从而允许你设定回调函数。

理解不够,参考下面

/article/4594977.html

http://gashero.yeax.com/?p=70
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: