Python并行编程(八):with语法
2024-08-22 20:19:50
1、基本概念
当有两个相关的操作需要在一部分代码块前后分别执行的时候,可以使用with语法自动完成。同时,使用with语法可以在特定的地方分配和释放资源,因此,with语法也叫作"上下文管理器"。在threading模快中,所有带有acquire()方法和release()方法的对象都可以使用上下文管理器。主要用于代码块的收尾工作。
也就是说,下面的对象可以使用with语法:
Lock、RLock、Condition、Semaphore
2、测试用例
# coding : utf-8 import threading
import logging logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-10s) %(message)s',) def threading_with(statement):
with statement:
logging.debug('%s acquired via with' % statement) def threading_not_with(statement):
statement.acquire()
try:
logging.debug('%s acquired directly' % statement)
finally:
statement.release() if __name__ == '__main__':
lock = threading.Lock()
rlock = threading.RLock()
condition = threading.Condition()
mutex = threading.Semaphore(1)
threading_synchronization_list = [lock, rlock, condition, mutex] for statement in threading_synchronization_list:
t1 = threading.Thread(target=threading_with, args=(statement,))
t2 = threading.Thread(target=threading_not_with, args=(statement,))
t1.start()
t2.start()
t1.join()
t2.join()
最新文章
- React学习系列一
- android lsitview setOnItemLongClickListener 无效或不执行
- hdu 1573 x问题(中国剩余定理)HDU 2007-1 Programming Contest
- PS基础学习
- setTimeout的妙用2——防止循环超时
- 对百度WebUploader的二次封装,精简前端代码之图片预览上传(两句代码搞定上传)
- Html表单标签:
- git自定义项目钩子和全局钩子
- Android 播放内部mp3音乐
- IBM websphere MQ使用说明
- IDEA中Git的使用基础
- C#代码实现邮箱验证C#中及一些常用的正则表达式
- Null Hypothesis and Alternate Hypothesis
- DCL,即Double Check Lock,中卫双重检查锁定。
- BZOJ3142 HNOI2013数列(组合数学)
- 20155225 2016-2017-2 《Java程序设计》第一周学习总结
- WindowsPhone模拟简易Toast弹出框
- JAVA之Map使用
- Vue.js:自定义指令
- Promise个人笔记---【Promise的前世今生】