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 )

  • 相关阅读:
    MVC,KVO,KVC的简单认识
    Objective-C之集合对象
    Objective-C之词典对象
    Objective-C之数组对象
    Objective-C关键字static
    IOS做天气预报
    同步和异步GET,POST请求
    iOS开发常用的开源库和示例
    KVC KVO KVB
    iOS中的 沙盒文件夹 (数据的写入和读取,归档和反归档)
  • 原文地址:https://www.cnblogs.com/forrestju/p/3380786.html
Copyright © 2011-2022 走看看