greenlet实践
作者: | gashero |
---|---|
日期: | 2009-06-16 |
1 简介
本想依靠它实现异步转同步,试试看吧。
2 一个异步转同步的例子,使用Twisted
将Twisted中的异步改为同步了:
#! /usr/bin/env python # -*- coding: UTF-8 -*- # File: readcall.py # Date: 2009-06-16 # Author: gashero """ 测试Greenlet与Twisted合用,实现异步改同步调用 """ import os import sys import greenlet from twisted.internet import reactor,protocol from twisted.protocols import basic from twisted.python import log def wait_host(): return class RCProtocol(basic.LineReceiver): def connectionMade(self): print 'connection made' self.grrc=greenlet.greenlet(self.read_chunk) self.grrc.switch() #切换到处理函数read_chunk() print 'switched to grrc' return def connectionLost(self,reason): print 'connection lost' return def _dataReceived(self,data): return def lineReceived(self,line): print 'line Received' self.grrc.switch(line) return def read_chunk(self): while True: #死循环中处理每次读取数据成功 print 'in read_chunk()' g_self=greenlet.getcurrent() chunk=g_self.parent.switch() #切换到主循环的greenlet,等被切换回来时就返回了传递的数据了 if 'quit' in chunk.lower(): self.transport.write('HTTP/1.1 200 OK\r\nContent-Length:10\r\n\r\nHelloWorld') self.transport.loseConnection() break return class RCFactory(protocol.ServerFactory): protocol=RCProtocol def main(): log.startLogging(sys.stdout) reactor.listenTCP(8090,RCFactory()) reactor.run() return if __name__=='__main__': main()