zoukankan      html  css  js  c++  java
  • Twisted 使用多线程

    Twisted 提供主线程和辅线程,主线程只有1个,即reactor.run(),辅线程有多个,可以自由配置

    Twisted 大多数代码运行在主线程中,dataReceived(),connectionLose()等事件处理函数由主线程调用,如果耗时太长,可以将其移到辅助线程中处理

    同时,Twisted框架中大多数内置函数都不是线程安全的,因此需要将内置函数放入主线程中,否则会导致逻辑错误或者系统崩溃

    1、使代码运行在主线程中

    如果其他线程中需要执行非线程安全的Twisted内置函数,可以使用reactor.callFromThread()函数使代码运行在主线程中

    from twisted.internet import reactor,defer
    import Myprotocol
    
    protocol = Myprotocol()
    def must_run_in_main_thread(message):
        protocol.send = True
        protocol.transport.write(message)
    
    def run_in_any_thread():
        reactor.callFromThread(must_run_in_main_thread,'good')
        print('the run of must_run_in_main_thread has been finashed')
    callFromThread将自己的线程在调用处挂起。直到被调用的函数已经在主线程中完成
    注:
    callFromThread不仅可以是twisted的辅助线程,还可以是twisted主线程,或是python threading库建立的线程

    2、在辅助线程中运行

    在主线程中遇到比较耗时的处理时,可以用reactor.callInThread()函数建立辅助线程任务

    from twisted.internet import reactor,defer
    from twisted.internet.protocol import DatagramProtocol
    
    def long_operation(msg):
        import time 
        time.sleep(10)
        print('10秒后获取信息',msg)
    
    class Echo(DatagramProtocol):
        def datagramReceived(self, datagram, addr):
            # 调用long_operation,在辅助线程中执行,本调用在主线程中立即返回
            reactor.callInThread(long_operation,datagram.decode('utf8'))
    
    protocol = Echo()
    reactor.listenUDP(8007,protocol)
    reactor.run()

    3、配置线程池

    可以使用reactor.suggestThreadPoolsize(10),定义线程数量

  • 相关阅读:
    深入浅出TCP之listen
    indexing and hashing
    c++四种强制类型转化
    c++实现web服务框架
    MVC、MVP、MVVM概念解析
    常用设计模式
    [React]虚拟DOM
    防抖和节流
    函数柯里化
    apply, bind, call方法剖析
  • 原文地址:https://www.cnblogs.com/Erick-L/p/7088111.html
Copyright © 2011-2022 走看看