Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5119364
  • 博文数量: 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

2016-09-04 13:09:05



Twisted是基于异步模式的开发框架,因而利用Twisted进行非阻塞编程自然也是必会的用法,下面我们就来一起看一下使用Python的Twisted框架编写非阻塞程序的代码示例:


  1. # For years we thought this was all there was... We kept hiring more
  2. # developers, more managers and buying servers. We were trying harder
  3. # optimising processes and fire-fighting while getting mediocre
  4. # performance in return. Till luckily one day our hosting
  5. # company decided to increase their fees and we decided to
  6. # switch to Twisted Ltd.!
  7.   
  8. from twisted.internet import reactor
  9. from twisted.internet import defer
  10. from twisted.internet import task
  11.   
  12. # Twisted has a slightly different approach
  13. def schedule_install(customer):
  14.   # They are calling us back when a Wordpress installation completes.
  15.   # They connected the caller recognition system with our CRM and
  16.   # we know exactly what a call is about and what has to be done next.
  17.   #
  18.   # We now design processes of what has to happen on certain events.
  19.   def schedule_install_wordpress():
  20.       def on_done():
  21.         print "Callback: Finished installation for", customer
  22.     print "Scheduling: Installation for", customer
  23.     return task.deferLater(reactor, 3, on_done)
  24.   #
  25.   def all_done(_):
  26.     print "All done for", customer
  27.   #
  28.   # For each customer, we schedule these processes on the CRM
  29.   # and that
  30.   # is all our chief-Twisted developer has to do
  31.   d = schedule_install_wordpress()
  32.   d.addCallback(all_done)
  33.   #
  34.   return d
  35.   
  36. # Yes, we don't need many developers anymore or any synchronization.
  37. # ~~ Super-powered Twisted developer ~~
  38. def twisted_developer_day(customers):
  39.   print "Goodmorning from Twisted developer"
  40.   #
  41.   # Here's what has to be done today
  42.   work = [schedule_install(customer) for customer in customers]
  43.   # Turn off the lights when done
  44.   join = defer.DeferredList(work)
  45.   join.addCallback(lambda _: reactor.stop())
  46.   #
  47.   print "Bye from Twisted developer!"
  48. # Even his day is particularly
  49. twisted_developer_day(["Customer %d" % i for i in xrange(15)])
  50.   
  51. # Reactor, our secretary uses the CRM and follows-up on
  52. reactor.run()

运行结果:

  1. ------ Running example 3 ------
  2. Goodmorning from Twisted developer
  3. Scheduling: Installation for Customer 0
  4. ....
  5. Scheduling: Installation for Customer 14
  6. Bye from Twisted developer!
  7. Callback: Finished installation for Customer 0
  8. All done for Customer 0
  9. Callback: Finished installation for Customer 1
  10. All done for Customer 1
  11. ...
  12. All done for Customer 14
  13. * Elapsed time: 3.18 seconds

这次我们得到了完美的执行代码和可读性强的输出结果,并且没有使用线程。我们并行地处理了15个消费者,也就是说,本来需要45s的执行时间在3s之内就已经完成。这个窍门就是我们把所有的阻塞的对sleep()的调用都换成了Twisted中对等的task.deferLater()和回调函数。由于现在处理的操作在其他地方进行,我们就可以毫不费力地同时服务于15个消费者。
前面提到处理的操作发生在其他的某个地方。现在来解释一下,算术运算仍然发生在CPU内,但是现在的CPU处理速度相比磁盘和网络操作来说非常快。所以给CPU提供数据或者从CPU向内存或另一个CPU发送数据花费了大多数时间。我们使用了非阻塞的操作节省了这方面的时间,例如,task.deferLater()使用了回调函数,当数据已经传输完成的时候会被激活。
另一个很重要的一点是输出中的Goodmorning from Twisted developer和Bye from Twisted developer!信息。在代码开始执行时就已经打印出了这两条信息。如果代码如此早地执行到了这个地方,那么我们的应用真正开始运行是在什么时候呢?答案是,对于一个Twisted应用(包括Scrapy)来说是在reactor.run()里运行的。在调用这个方法之前,必须把应用中可能用到的每个Deferred链准备就绪,然后reactor.run()方法会监视并激活回调函数。
注意,reactor的主要一条规则就是,你可以执行任何操作,只要它足够快并且是非阻塞的。
现在好了,代码中没有那么用于管理多线程的部分了,不过这些回调函数看起来还是有些杂乱。可以修改成这样:


  1. # Twisted gave us utilities that make our code way more
  2. @defer.inlineCallbacks
  3. def inline_install(customer):
  4.   print "Scheduling: Installation for", customer
  5.   yield task.deferLater(reactor, 3, lambda: None)
  6.   print "Callback: Finished installation for", customer
  7.   print "All done for", customer
  8.   
  9. def twisted_developer_day(customers):
  10.   ... same as previously but using inline_install() instead of schedule_install()
  11.   
  12. twisted_developer_day(["Customer %d" % i for i in xrange(15)])
  13. reactor.run()

运行的结果和前一个例子相同。这段代码的作用和上一个例子是一样的,但是看起来更加简洁明了。inlineCallbacks生成器可以使用一些一些Python的机制来使得inline_install()函数暂停或者恢复执行。inline_install()函数变成了一个Deferred对象并且并行地为每个消费者运行。每次yield的时候,运行就会中止在当前的inline_install()实例上,直到yield的Deferred对象完成后再恢复运行。

现在唯一的问题是,如果我们不止有15个消费者,而是有,比如10000个消费者时又该怎样?这段代码会同时开始10000个同时执行的序列(比如HTTP请求、数据库的写操作等等)。这样做可能没什么问题,但也可能会产生各种失败。在有巨大并发请求的应用中,例如Scrapy,我们经常需要把并发的数量限制到一个可以接受的程度上。在下面的一个例子中,我们使用task.Cooperator()来完成这样的功能。Scrapy在它的Item Pipeline中也使用了相同的机制来限制并发的数目(即CONCURRENT_ITEMS设置):


  1. @defer.inlineCallbacks
  2. def inline_install(customer):
  3.   ... same as above
  4.   
  5. # The new "problem" is that we have to manage all this concurrency to
  6. # avoid causing problems to others, but this is a nice problem to have.
  7. def twisted_developer_day(customers):
  8.   print "Goodmorning from Twisted developer"
  9.   work = (inline_install(customer) for customer in customers)
  10.   #
  11.   # We use the Cooperator mechanism to make the secretary not
  12.   # service more than 5 customers simultaneously.
  13.   coop = task.Cooperator()
  14.   join = defer.DeferredList([coop.coiterate(work) for i in xrange(5)])
  15.   #
  16.   join.addCallback(lambda _: reactor.stop())
  17.   print "Bye from Twisted developer!"
  18.   
  19. twisted_developer_day(["Customer %d" % i for i in xrange(15)])
  20. reactor.run()
  21.   
  22. # We are now more lean than ever, our customers happy, our hosting
  23. # bills ridiculously low and our performance stellar.
  24. # ~*~ THE END ~*~

运行结果:

  1. $ ./deferreds.py 5
  2. ------ Running example 5 ------
  3. Goodmorning from Twisted developer
  4. Bye from Twisted developer!
  5. Scheduling: Installation for Customer 0
  6. ...
  7. Callback: Finished installation for Customer 4
  8. All done for Customer 4
  9. Scheduling: Installation for Customer 5
  10. ...
  11. Callback: Finished installation for Customer 14
  12. All done for Customer 14
  13. * Elapsed time: 9.19 seconds

从上面的输出中可以看到,程序运行时好像有5个处理消费者的槽。除非一个槽空出来,否则不会开始处理下一个消费者的请求。在本例中,处理时间都是3秒,所以看起来像是5个一批次地处理一样。最后得到的性能跟使用线程是一样的,但是这次只有一个线程,代码也更加简洁更容易写出正确的代码。

PS:deferToThread使同步函数实现非阻塞
wisted的defer.Deferred (from twisted.internet import defer)可以返回一个deferred对象.

注:deferToThread使用线程实现的,不推荐过多使用
***把同步函数变为异步(返回一个Deferred)***
twisted的deferToThread(from twisted.internet.threads import deferToThread)也返回一个deferred对象,不过回调函数在另一个线程处理,主要用于数据库/文件读取操作


  1. ..
  2.   
  3. # 代码片段
  4.   
  5.   def dataReceived(self, data):
  6.     now = int(time.time())
  7.   
  8.     for ftype, data in self.fpcodec.feed(data):
  9.       if ftype == 'oob':
  10.         self.msg('OOB:', repr(data))
  11.       elif ftype == 0x81: # 对服务器请求的心跳应答(这个是解析 防疲劳驾驶仪,发给gps上位机的,然后上位机发给服务器的)
  12.         self.msg('FP.PONG:', repr(data))
  13.       else:
  14.         self.msg('TODO:', (ftype, data))
  15.       d = deferToThread(self.redis.zadd, "beier:fpstat:fps", now, self.devid)
  16.       d.addCallback(self._doResult, extra)

下面这儿完整的例子可以给大家参考一下

  1. # -*- coding: utf-8 -*-
  2.   
  3. from twisted.internet import defer, reactor
  4. from twisted.internet.threads import deferToThread
  5.   
  6. import functools
  7. import time
  8.   
  9. # 耗时操作 这是一个同步阻塞函数
  10. def mySleep(timeout):
  11.   time.sleep(timeout)
  12.   
  13.   # 返回值相当于加进了callback里
  14.   return 3
  15.   
  16. def say(result):
  17.   print "耗时操作结束了, 并把它返回的结果给我了", result
  18.   
  19. # 用functools.partial包装一下, 传递参数进去
  20. cb = functools.partial(mySleep, 3)
  21. d = deferToThread(cb)
  22. d.addCallback(say)
  23.   
  24. print "你还没有结束我就执行了, 哈哈"
  25.   
  26. reactor.run()

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