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()

最新文章

  1. React学习系列一
  2. android lsitview setOnItemLongClickListener 无效或不执行
  3. hdu 1573 x问题(中国剩余定理)HDU 2007-1 Programming Contest
  4. PS基础学习
  5. setTimeout的妙用2——防止循环超时
  6. 对百度WebUploader的二次封装,精简前端代码之图片预览上传(两句代码搞定上传)
  7. Html表单标签:
  8. git自定义项目钩子和全局钩子
  9. Android 播放内部mp3音乐
  10. IBM websphere MQ使用说明
  11. IDEA中Git的使用基础
  12. C#代码实现邮箱验证C#中及一些常用的正则表达式
  13. Null Hypothesis and Alternate Hypothesis
  14. DCL,即Double Check Lock,中卫双重检查锁定。
  15. BZOJ3142 HNOI2013数列(组合数学)
  16. 20155225 2016-2017-2 《Java程序设计》第一周学习总结
  17. WindowsPhone模拟简易Toast弹出框
  18. JAVA之Map使用
  19. Vue.js:自定义指令
  20. Promise个人笔记---【Promise的前世今生】

热门文章

  1. 一款纯html5实现的时钟
  2. kernel 4.4.12 移植 HUAWEI MU609 Mini PCIe Module
  3. Ubuntu下安装SSH服务
  4. 构造 - HDU 5402 Travelling Salesman Problem
  5. 日期-date.js
  6. C++ 函数的扩展④--函数重载与函数指针
  7. sizeof 数组与指针
  8. Angular ViewChild
  9. THINKPHP5加载公共头部尾部模板方法
  10. ionic ui 框架