Python并行编程(八):with语法
生活随笔
收集整理的這篇文章主要介紹了
Python并行编程(八):with语法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1、基本概念
? ? ? 當(dāng)有兩個相關(guān)的操作需要在一部分代碼塊前后分別執(zhí)行的時候,可以使用with語法自動完成。同時,使用with語法可以在特定的地方分配和釋放資源,因此,with語法也叫作"上下文管理器"。在threading模快中,所有帶有acquire()方法和release()方法的對象都可以使用上下文管理器。主要用于代碼塊的收尾工作。
? ? ? 也就是說,下面的對象可以使用with語法:
? ? ? ? ? ? Lock、RLock、Condition、Semaphore
?
2、測試用例
# coding : utf-8import threading import logginglogging.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()
?
轉(zhuǎn)載于:https://www.cnblogs.com/dukuan/p/9798036.html
總結(jié)
以上是生活随笔為你收集整理的Python并行编程(八):with语法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 漫画:禅道程序员的一天
- 下一篇: 早就听闻天涯娱版藏龙卧虎,特来求高人扒一