Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4995855
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2011-12-08 13:37:05

 

来源: http://pako.iteye.com/blog/978829

最近小试了下twisted,还是发现用起来挺方便的,加之本身就是python开发的,用来开发一些server还是很效率,主要是twisted把很多事都帮你处理好了。

最后看了http://twistedmatrix.com/documents/current/core/howto/gendefer.html后发现

deferred主要做的事情就是将一些可能会耗时,会阻塞主线程的事放到另一个线程中去做,然后返回一个deferred对象给主线程,主线程给这个deferred注册一些回调函数,当在子线程中耗时的函数处理完后会调用deferred的callback函数,调用之前注册好的回调函数,一次实现异步操作。

 

  1. import time
  2. def largeFibonnaciNumber():
  3.     """
  4.     耗时的事
  5.     """
  6.     TARGET = 10000

  7.     first = 0
  8.     second = 1
  9.     
  10.     for i in xrange(TARGET - 1):
  11.         new = first + second
  12.         first = second
  13.         second = new
  14.     time.sleep(3)
  15.     return second

  16. from twisted.internet import threads, reactor

  17. def fibonacciCallback(result):
  18.     """
  19.     回调函数
  20.     打印耗时函数的返回结果
  21.     """
  22.     print "largeFibonnaciNumber result =", result

  23. def run():
  24.     """
  25.     主函数
  26.     """
  27.     # 将耗时函数放入另一个线程执行,返回一个deferred对象
  28.     d = threads.deferToThread(largeFibonnaciNumber)
  29.     # 添加回调函数
  30.     d.addCallback(fibonacciCallback)
  31.     print "1st line after the addition of the callback"
  32.     print "2nd line after the addition of the callback"

  33. if __name__ == '__main__':
  34.     run()
  35.     reactor.run()

 

 

阅读(1525) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~