python里协程使用同步锁Lock

来源:互联网 发布:php server 编辑:程序博客网 时间:2024/06/10 07:25
尽管asyncio库是使用单线程来实现协程的,但是它还是并发的,乱序执行的。可以说是单线程的调度系统,并且由于执行时有延时或者I/O中断等因素,每个协程如果同步时,还是得使用一些同步对象来实现。
比如asyncio就定义了一个锁对象Lock,它一次只允许一个协程来访问共享的资源,如果多协程想访问就会阻塞起来,也就是说如果一个协程没有释放这个锁,别的协程是没有办法访问共享的资源。

例子:

import asyncioimport functoolsdef unlock(lock):    print('callback releasing lock')    lock.release()async def coro1(lock):    print('coro1 waiting for the lock')    with await lock:        print('coro1 acquired lock')    print('coro1 released lock')async def coro2(lock):    print('coro2 waiting for the lock')    await lock    try:        print('coro2 acquired lock')    finally:        print('coro2 released lock')        lock.release()async def main(loop):    # Create and acquire a shared lock.    lock = asyncio.Lock()    print('acquiring the lock before starting coroutines')    await lock.acquire()    print('lock acquired: {}'.format(lock.locked()))    # Schedule a callback to unlock the lock.    loop.call_later(0.1, functools.partial(unlock, lock))    # Run the coroutines that want to use the lock.    print('waiting for coroutines')    await asyncio.wait([coro1(lock), coro2(lock)]),event_loop = asyncio.get_event_loop()try:    event_loop.run_until_complete(main(event_loop))finally:    event_loop.close()
输出结果如下:

acquiring the lock before starting coroutines
lock acquired: True
waiting for coroutines
coro1 waiting for the lock
coro2 waiting for the lock
callback releasing lock
coro1 acquired lock
coro1 released lock
coro2 acquired lock
coro2 released lock

Python游戏开发入门

http://edu.csdn.net/course/detail/5690

你也能动手修改C编译器

http://edu.csdn.net/course/detail/5582

纸牌游戏开发

http://edu.csdn.net/course/detail/5538 

五子棋游戏开发

http://edu.csdn.net/course/detail/5487
RPG游戏从入门到精通
http://edu.csdn.net/course/detail/5246
WiX安装工具的使用
http://edu.csdn.net/course/detail/5207
俄罗斯方块游戏开发
http://edu.csdn.net/course/detail/5110
boost库入门基础
http://edu.csdn.net/course/detail/5029
Arduino入门基础
http://edu.csdn.net/course/detail/4931
Unity5.x游戏基础入门
http://edu.csdn.net/course/detail/4810
TensorFlow API攻略
http://edu.csdn.net/course/detail/4495
TensorFlow入门基本教程
http://edu.csdn.net/course/detail/4369
C++标准模板库从入门到精通 
http://edu.csdn.net/course/detail/3324
跟老菜鸟学C++
http://edu.csdn.net/course/detail/2901
跟老菜鸟学python
http://edu.csdn.net/course/detail/2592
在VC2015里学会使用tinyxml库
http://edu.csdn.net/course/detail/2590
在Windows下SVN的版本管理与实战 
http://edu.csdn.net/course/detail/2579
Visual Studio 2015开发C++程序的基本使用 
http://edu.csdn.net/course/detail/2570
在VC2015里使用protobuf协议
http://edu.csdn.net/course/detail/2582
在VC2015里学会使用MySQL数据库
http://edu.csdn.net/course/detail/2672




原创粉丝点击