Python 線程,with的作用(自動獲取和釋放鎖Lock)


Python 線程,with的作用(自動獲取和釋放鎖Lock)

import threading
import time
 
num=0  #全局變量多個線程可以讀寫,傳遞數據
mutex=threading.Lock() #創建一個鎖
 
class Mythread(threading.Thread):
    def run(self):
        global num
        with mutex:   #with Lock的作用相當於自動獲取和釋放鎖(資源)
            for i in range(1000000): #鎖定期間,其他線程不可以干活
                num+=1
        print(num)
 
mythread=[]
for i  in range(5):
    t=Mythread()
    t.start()
    mythread.append(t)
for t in mythread:
    t.join()
print("game over")
 
'''
    with mutex:   #with表示自動打開自動釋放鎖
        for i in range(1000000): #鎖定期間,其他人不可以干活
            num+=1
#上面的和下面的是等價的
    if mutex.acquire(1):#鎖住成功繼續干活,沒有鎖住成功就一直等待,1代表獨占
        for i in range(1000000): #鎖定期間,其他線程不可以干活
            num+=1
        mutex.release() #釋放鎖
'''

 

python3,淺談with的神奇魔法


在實際的編碼過程中,有時有一些任務,需要事先做一些設置,事后做一些清理,這時就需要python with出場了,with能夠對這樣的需求進行一個比較優雅的處理,最常用的例子就是對訪問文件的處理。

一般訪問文件資源時我們會這樣處理:

f = open(r'c:\test.txt', 'r')
data = f.read()
f.close()
這樣寫沒有錯,但是容易犯兩個毛病:
1. 如果在讀寫時出現異常而忘了異常處理。
2. 忘了關閉文件句柄

以下的加強版本的寫法:

f = open(r'c:\test.txt', 'r')
try:
    data = f.read()
finally:
    f.close()
以上的寫法就可以避免因讀取文件時異常的發生而沒有關閉問題的處理了。代碼長了一些。
但使用with有更優雅的寫法:

with open(r'c:\test.txt', 'r') as f:
    data = f.read()
說明:
with后面接的對象返回的結果賦值給f。此例當中open函數返回的文件對象賦值給了f.with會自已獲取上下文件的異常信息。
with是如何做到的呢?
with后面返回的對象要求必須兩__enter__()/__exit__()這兩個方法,而文件對象f剛好是有這兩個方法的,故應用自如。
pytho中官方定義說明如下(https://docs.python.org/2/reference/datamodel.html#context-managers):

object.__enter__(self)
進入與此對象相關的運行時上下文。with語句將將此方法的返回值綁定到語句的AS子句中指定的目標(如果有設置的話)

object.__exit__(self, exc_type, exc_value, traceback)
退出與此對象相關的運行時上下文。參數描述導致上下文退出的異常。如果上下文運行時沒有異常發生,那么三個參數都將置為None。
如果有異常發生,並且該方法希望抑制異常(即阻止它被傳播),則它應該返回True。否則,異常將在退出該方法時正常處理。

請注意, __exit__()方法不應該重新拋出傳入的異常,這是調用者的職責。
下面舉例說明他的原理:

1. 無異常發生時的例子:

#!/user/bin/env python3
#-*- coding:utf-8 -*-

class Test:
    def __enter__(self):
        print('__enter__() is call!')
        return self

    def dosomething(self):
        print('dosomethong!')

    def __exit__(self, exc_type, exc_value, traceback):
        print('__exit__() is call!')
        print(f'type:{exc_type}')
        print(f'value:{exc_value}')
        print(f'trace:{traceback}')
        print('__exit()__ is call!')

with Test() as sample:
    sample.dosomething()

>>
__enter__() is call!
dosomethong!
__exit__() is call!
type:None
value:None
trace:None
__exit()__ is call!
以上的實例Text,我們注意到他帶有__enter__()/__exit__()這兩個方法,當對象被實例化時,就會主動調用__enter__()方法,任務執行完成后就會調用__exit__()方法,另外,注意到,__exit__()方法是帶有三個參數的(exc_type, exc_value, traceback), 依據上面的官方說明:如果上下文運行時沒有異常發生,那么三個參數都將置為None, 這里三個參數由於沒有發生異常,的確是置為了None, 與預期一致. 

2. 有異常發生時,會拋出異常的例子:
以下例子在上面稍做了一些修改,讓運行時產生異常,看看這三個參數的賦值情況:

#!/user/bin/env python3
#-*- coding:utf-8 -*-

class Test:
    def __enter__(self):
        print('__enter__() is call!')
        return self

    def dosomething(self):
        x = 1/0
        print('dosomethong!')

    def __exit__(self, exc_type, exc_value, traceback):
        print('__exit__() is call!')
        print(f'type:{exc_type}')
        print(f'value:{exc_value}')
        print(f'trace:{traceback}')
        print('__exit()__ is call!')
        # return True


with Test() as sample:
    sample.dosomething()
>>
__enter__() is call!
Traceback (most recent call last):
__exit__() is call!
type:<class 'ZeroDivisionError'>
  File "C:/Users/xxx/PycharmProjects/Test1/test.py", line 23, in <module>
value:division by zero
    sample.dosomething()
trace:<traceback object at 0x000001C08CF32F88>
  File "C:/Users/xxx/PycharmProjects/Test1/test.py", line 10, in dosomething
__exit()__ is call!
    x = 1/0
ZeroDivisionError: division by zero
從結果可以看出, 在執行到dosomethong時就發生了異常,然后將異常傳給了__exit__(), 依據上面的官方說明:如果有異常發生,並且該方法希望抑制異常(即阻止它被傳播),則它應該返回True。否則,異常將在退出該方法時正常處理。當前__exit__並沒有寫明返回True,故會拋出異常,也是合理的,但是正常來講,程序應該是不希望它拋出異常的,這也是調用者的職責,我們將再次修改__exit__, 將其返回設置為True, 

3. 有異常發生時,不再拋出異常的例子:

在上面的例子上做點修改.
#!/user/bin/env python3
#-*- coding:utf-8 -*-

class Test:
    def __enter__(self):
        print('__enter__() is call!')
        return self

    def dosomething(self):
        x = 1/0
        print('dosomethong!')

    def __exit__(self, exc_type, exc_value, traceback):
        print('__exit__() is call!')
        print(f'type:{exc_type}')
        print(f'value:{exc_value}')
        print(f'trace:{traceback}')
        print('__exit()__ is call!')
        return True


with Test() as sample:
    sample.dosomething()

>>
__enter__() is call!
__exit__() is call!
type:<class 'ZeroDivisionError'>
value:division by zero
trace:<traceback object at 0x000001C94E592F88>
__exit()__ is call!
從結果看,異常拋出被抑制了,符合預期。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM