zoukankan      html  css  js  c++  java
  • python中协程的使用示例

    例子1 把字符串分割为列表

    def line_splitter( delimiter = None ):
      print( 'ready to split' )
      result = None
      while True:
        line = (yield result)
        result = line.split( delimiter )

    if __name__ == '__main__':
      s = line_splitter(',')
      print( 'inital:' )
      next( s )
      print( 'call 1: ', s.send( 'a, b, c' ) )
      print( 'call 2: ', s.send( '100, 200, 300' ) )

    例子2 用协程管理共享数据

    def access_socket_map():
    # socket map维护协程
      socket_map = { } # 连接客户端的socket字典 {UUID->socket}
      last_cmd = None
      elem = None
      while True:
        if last_cmd == 'POP':
          args = (yield elem)
        else:
          args = (yield)
        operation = args[0]
        if operation == 'PUT':
          socket_map[ args[1] ] = args[2]
        elif operation == 'POP':
          elem = socket_map.pop( args[1] )
        last_cmd = operation


    if __name__ == '__main__':
      cr = access_socket_map()
      next( cr )
      cr.send( ['PUT', 1, 123] )
      print( cr.send( ['POP', 1] ) + 1 )

  • 相关阅读:
    初识SpringBoot
    Dubbo案例SSM整合
    Dubbo
    Spring错题整合
    SSM整合
    SpringMVC数据校验
    SpringMVC拦截器
    SpringMVC文件上传
    SpringMVC异常
    字符串
  • 原文地址:https://www.cnblogs.com/forrestju/p/3380786.html
Copyright © 2011-2022 走看看