博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
初识Twisted(一)
阅读量:4656 次
发布时间:2019-06-09

本文共 1439 字,大约阅读时间需要 4 分钟。

pip install Twisted

安装Twisted库

 

from twisted.internet import reactor#开启事件循环#不是简单的循环#不会带来任何性能损失reactor.run()

1. Twisted的reactor只有通过调用reactor.run()才启动。

2. reactor循环是在其开始的线程中运行,也就是运行在主线程中。

3. 一旦启动,reactor就会在程序的控制下(或者具体在一个启动它的线程的控制下)一直运行下去。

4. reactor空转时并不会消耗任何CPU的资

5. 并不需要显式的创建reactor,只需要引入就OK。

 

from twisted.internet import pollreactor#将会使用poll而不是默认的selectpollreactor.install()

一般的写法:

from twited.internet import pollreactorpollreactor.install()from twisted.internet import reactoreactor.run()

一个简单的demo

#一个简单的demofrom twisted.internet import reactordef hello():        print('hello from the reactor loop!')        print('hhh')reactor.callWhenRunning(hello)print('start the reactor')reactor.run()

 回调的重要特性:

1. 我们的代码与Twisted代码运行在同一个线程中。

2. 当我们的代码运行时,Twisted代码是处于暂停状态的。

3. 同样,当Twisted代码处于运行状态时,我们的代码处于暂停状态。

4. reactor事件循环会在我们的回调函数返回后恢复运

 

 

特别需要强调的是,我们应该尽量避免在回调函数中使用会阻塞I/O的函数。

from twisted.internet import reactorclass Countdown(object):        counter = 5        def count(self):                if self.counter == 0:                        #reactor停止                        reactor.stop()                else:                        print(self.counter, '...')                        self.counter -= 1                        #注册回调函数                        reactor.callLater(1, self.count)#添加reactor将要执行的函数reactor.callWhenRunning(Countdown().count)#开始print('start')reactor.run()#结束print('stop')

 

转载于:https://www.cnblogs.com/yangzixiong/p/10720798.html

你可能感兴趣的文章
JS中window.event事件使用详解
查看>>
ES6深入学习记录(一)class方法相关
查看>>
C语言对mysql数据库的操作
查看>>
INNO SETUP 获得命令行参数
查看>>
HTML5与CSS3权威指南之CSS3学习记录
查看>>
docker安装部署
查看>>
AVL树、splay树(伸展树)和红黑树比较
查看>>
多媒体音量条显示异常跳动
查看>>
运算符及题目(2017.1.8)
查看>>
ssh自动分发密匙脚本样板
查看>>
转 小辉_Ray CORS(跨域资源共享)
查看>>
Linux安装postgresql
查看>>
MyBatis启动:MapperStatement创建
查看>>
【 全干货 】5 分钟带你看懂 Docker !
查看>>
[转]优化Flash性能
查看>>
popStar手机游戏机机对战程序
查看>>
lambda表达式树
查看>>
二次注入原理及防御
查看>>
会话记住已登录功能
查看>>
Linux内核分析——可执行程序的装载
查看>>