一、線程共享進程資源
每個線程互相獨立,相互之間沒有任何關系,但是在同一個進程中的資源,線程是共享的,如果不進行資源的合理分配,對數據造成破壞,使得線程運行的結果不可預期。這種現象稱為“線程不安全”。
實例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#-*- coding: utf-8 -*- import threading import time def test_xc(): f = open ( "test.txt" , "a" ) f.write( "test_dxc" + '\n' ) time.sleep( 1 ) f.close() if __name__ = = '__main__' : for i in xrange ( 5 ): t = threading.thread(target = test_xc) t.start() |
結果展示:
二、互斥鎖同步
線程同步能夠保證多個線程安全訪問競爭資源,最簡單的同步機制是引入互斥鎖?;コ怄i為資源引入一個狀態:鎖定/非鎖定。某個線程要更改共享數據時,先將其鎖定,此時資源的狀態為“鎖定”,其他線程不能更改;直到該線程釋放資源,將資源的狀態變成“非鎖定”,其他的線程才能再次鎖定該資源?;コ怄i保證了每次只有一個線程進行寫入操作,從而保證了多線程情況下數據的正確性。
threading模塊中定義了lock類,可以方便的處理鎖定:
1
2
3
4
5
6
|
#創建鎖 mutex = threading.lock() #鎖定 mutex.acquire([timeout]) #timeout是超時時間 #釋放 mutex.release() |
其中,鎖定方法acquire可以有一個超時時間的可選參數timeout。如果設定了timeout,則在超時后通過返回值可以判斷是否得到了鎖,從而可以進行一些其他的處理。
三、使用線程鎖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<pre name = "code" class = "python" > #-*- coding: utf-8 -*- import threading import time def test_xc(): f = open ( "test.txt" , "a" ) f.write( "test_dxc" + '\n' ) time.sleep( 1 ) mutex.acquire() #取得鎖 f.close() mutex.release() #釋放鎖 if __name__ = = '__main__' : mutex = threading.lock() #創建鎖 for i in xrange ( 5 ): t = threading.thread(target = test_xc) t.start() |
運行結果
以上這篇對python多線程中互斥鎖threading.lock的簡單應用詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/baidu_24617085/article/details/50462497