twisted 线程里的几个函数

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)来终止它。但是这个方法会阻塞到主循环。

  1. #coding=utf-8
  2. from twisted.internet import reactor
  3. import time
  4. def tt(i,j):
  5.     while 1:
  6.         print i,'---------------',j
  7.         time.sleep(1)

  8. reactor.callFromThread(tt,1,1)
  9. 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对象,从而允许你设定回调函数。

理解不够,参考下面

http://www.cnblogs.com/zhengyun_ustc/archive/2010/05/18/1738357.html

http://gashero.yeax.com/?p=70

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值