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 )

上一篇:【Python】协程


下一篇:Windows在结构FTPserver