VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python教程 >
  • python基础教程之Python3标准库:asyncio异步I/O、事件循环和并发工具(6)

本站最新发布   Python从入门到精通|Python基础教程
试听地址  
https://www.xin3721.com/eschool/pythonxin3721/


asyncio
  •  
  • async def phase(i):
  • print('in phase {}'.format(i))
  • await asyncio.sleep(0.5 - (0.1 * i))
  • print('done with phase {}'.format(i))
  • return 'phase {} result'.format(i)
  •  
  • async def main(num_phases):
  • print('starting main')
  • phases = [
  • phase(i)
  • for i in range(num_phases)
  • ]
  • print('waiting for phases to complete')
  • results = []
  • for next_to_complete in asyncio.as_completed(phases):
  • answer = await next_to_complete
  • print('received answer {!r}'.format(answer))
  • results.append(answer)
  • print('results: {!r}'.format(results))
  • return results
  •  
  • event_loop = asyncio.get_event_loop()
  • try:
  • event_loop.run_until_complete(main(3))
  • finally:
  • event_loop.close()
  • 这个例子启动了多个后台阶段,它们会按其启动顺序的逆序完成。消费生成器时,循环会使用await等待协程的结果。

    1.7 同步原语

    尽管asyncio应用通常作为单线程的进程运行,不过仍被构建为并发应用。由于I/0以及其他外部事件的延迟和中断,每个协程或任务可能按一种不可预知的顺序执行。为了支持安全的并发执行,asyncio包含了threading和multiprocessing模块中一些底层原语的实现。

    1.7.1 锁

    Lock可以用来保护对一个共享资源的访问。只有锁的持有者可以使用这个资源。如果有多个请求要得到这个锁,那么其将会阻塞,以保证一次只有一个持有者。

    
    
    1. import asyncio
    2. import functools
    3.  
    4. def unlock(lock):
    5. print('callback releasing lock')
    6. lock.release()
    7.  
    8. async def coro1(lock):
    9. print('coro1 waiting for the lock')
    10. async with lock:
    11. print('coro1 acquired lock')
    12. print('coro1 released lock')
    13.  
    14. async def coro2(lock):
    15. print('coro2 waiting for the lock')
    16. await lock.acquire()
    17. try:
    18. print('coro2 acquired lock')
    19. finally:
    20. print('coro2 released lock')
    21. lock.release()
    22.  
    23. async def main(loop):
    24. # Create and acquire a shared lock.
    25. lock = asyncio.Lock()
    26. print('acquiring the lock before starting coroutines')
    27. await lock.acquire()
    28. print('lock acquired: {}'.format(lock.locked()))
    29.  
    30. # Schedule a callback to unlock the lock.
    31. loop.call_later(0.1, functools.partial(unlock, lock))
    32.  
    33. # Run the coroutines that want to use the lock.
    34. print('waiting for coroutines')
    35. await asyncio.wait([coro1(lock), coro2(lock)]),
    36.  
    37. event_loop = asyncio.get_event_loop()
    38. try:
    39. event_loop.run_until_complete(main(event_loop))
    40. finally:
    41. event_loop.close()

    锁可以直接调用,使用await来得到,并且使用结束时可以调用release()方法释放锁,如这个例子中的coro2()所示。还可以结合with await关键字使用锁作为异步上下文管理器,如coro1()中所示。

     

    1.7.2 事件

    asyncio.Event基于threading.Event。它允许多个消费者等待某个事件发生,而不必寻找一个特定值与通知关联。 

    
    
    1. import asyncio
    2. import functools
    3.  
    4. def set_event(event):
    5. print('setting event in callback')
    6. event.set()
    7.  
    8. async def coro1(event):
    9. print('coro1 waiting for event')
    10. await event.wait()
    11. print('coro1 triggered')
    12.  
    13. async def coro2(event):
    14. print('coro2 waiting for event')
    15. await event.wait()
    16. print('coro2 triggered')
    相关教程