目錄
- 一.Python 執行緒互斥鎖和行程互斥鎖
- 1.創建執行緒互斥鎖
- 2.創建行程互斥鎖
- 二.行程互斥鎖 Lock 函式介紹
- 三.行程互斥鎖 Lock 使用
- 案例一:使用行程,但不使用互斥鎖
- 案例二:行程互斥鎖的使用
- 案例三:對全域變數累計求和看看計算結果
- 四.猜你喜歡
和前面講到的 Python 執行緒互斥鎖 Lock 類似,當有多個行程 Process 同時讀寫同一個檔案時,為了避免資料讀寫產生例外,我們需要為正在操作的行程加上互斥鎖,互斥鎖的原理不管是對執行緒 threading 還是對行程 Process 而言都是一樣,
一.Python 執行緒互斥鎖和行程互斥鎖
1.創建執行緒互斥鎖
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:Python 行程互斥鎖 Lock.py
@Time:2021/05/09 07:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程式人生的精彩需要堅持不懈地積累!
"""
# 匯入執行緒threading模塊
import threading
# 創建執行緒互斥鎖
mutex = threading.Lock()
2.創建行程互斥鎖
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:Python 行程互斥鎖 Lock.py
@Time:2021/05/09 07:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程式人生的精彩需要堅持不懈地積累!
"""
from multip# 匯入行程模塊
from multiprocessing import Process,Lock
# 創建行程互斥鎖
mutex = Lock()
注意匯入模塊的區別,不要混淆使用!
二.行程互斥鎖 Lock 函式介紹
acquire— 鎖定資源;release— 釋放資源;
三.行程互斥鎖 Lock 使用
案例一:使用行程,但不使用互斥鎖
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:Python 行程互斥鎖 Lock.py
@Time:2021/05/09 07:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程式人生的精彩需要堅持不懈地積累!
"""
from multiprocessing import Lock, Process
import time
import random
import os
def foo(i, mutex):
print('%s: %s is running' % (i, os.getpid()))
time.sleep(random.random())
print('%s:%s is done' % (i, os.getpid()))
if __name__ == '__main__':
mutex = Lock()
for i in range(10):
process = Process(target=foo, args=(i, mutex))
process.start()
'''
輸出結果:
0: 17008 is running
1: 5288 is running
2: 1228 is running
3: 9724 is running
4: 7520 is running
5: 10236 is running
3:9724 is done
6: 16452 is running
7: 13328 is running
0:17008 is done
8: 9356 is running
9: 16432 is running
8:9356 is done
2:1228 is done
5:10236 is done
9:16432 is done
7:13328 is done
4:7520 is done
6:16452 is done
1:5288 is done
'''
重輸出的結果來看,多個行程同時在操作,如果是對同一個檔案讀寫操作,很明顯已經亂套了,這并不是我們想要的;如果多行程在讀寫同一檔案時想要保證資料安全,必然需要加上互斥鎖 Lock,例如下面這個 demo ;
案例二:行程互斥鎖的使用
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:Python 行程互斥鎖 Lock.py
@Time:2021/05/09 07:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程式人生的精彩需要堅持不懈地積累!
"""
from multiprocessing import Lock, Process
import time
import random
import os
def foo(i, mutex):
mutex.acquire()
print('%s: %s is running' % (i, os.getpid()))
time.sleep(random.random())
print('%s:%s is done' % (i, os.getpid()))
mutex.release()
if __name__ == '__main__':
mutex = Lock()
for i in range(10):
process = Process(target=foo, args=(i, mutex))
process.start()
'''
輸出結果:
0: 6908 is running
0:6908 is done
1: 7976 is running
1:7976 is done
3: 7824 is running
3:7824 is done
2: 17328 is running
2:17328 is done
4: 7844 is running
4:7844 is done
5: 15900 is running
5:15900 is done
6: 12648 is running
6:12648 is done
7: 16516 is running
7:16516 is done
8: 17348 is running
8:17348 is done
9: 13180 is running
9:13180 is done
'''
完美,即便是對同一個檔案進行讀寫操作,行程 Process 使用互斥鎖 Lock 之后也不會造成資料混亂的問題,同時也提高了效率,完美解決案例一的問題!
案例三:對全域變數累計求和看看計算結果
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:Python 行程互斥鎖 Lock.py
@Time:2021/05/09 07:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程式人生的精彩需要堅持不懈地積累!
"""
# 匯入行程模塊
from multiprocessing import Process,Lock
num = 0
def get_sum1():
global num # 宣告全域變數
for i in range(10000):
num = num +1
print("get_sum1:",num)
def get_sum2():
global num # 宣告全域變數
for i in range(10000):
num = num + 1
print("get_sum2:", num)
def main():
global num # 宣告全域變數
p1 = Process(target=get_sum1)
p1.start()
p2 = Process(target=get_sum2)
p2.start()
p1.join()
p2.join()
print("main:",num)
if __name__ == "__main__":
main()
print("main exit")
'''
輸出結果:
get_sum1: 10000
get_sum2: 10000
main: 0
main exit
'''
可能有小伙伴會覺得很納悶,main 函式中得 num 值怎么會是 0 ,明明主行程/兩個子行程都用關鍵字 **global **宣告了全域變數,即便沒有互斥鎖,也應該是一個小于 20000 的亂數,在文章 Python 行程 Process 與執行緒 threading 區別 中有詳細講解,同一行程的所有執行緒共享該行程的所有資源,行程與行程之間資源相互獨立,互不影響(類似深拷貝);
上面的程式有三個行程,這就意味著 num 變數實際上有三份資源,其中兩個行程對 num 分別做了 10000 次累計加 1 ,所以每個子行程的值都是 10000 ,主行程沒有對 num 任何操作,所以主行程 num 值為 0 ;
四.猜你喜歡
- Python 條件推導式
- Python 串列推導式
- Python 字典推導式
- Python 不定長參數 *argc/**kargcs
- Python 匿名函式 lambda
- Python return 邏輯判斷運算式
- Python is 和 == 區別
- Python 可變資料型別和不可變資料型別
- Python 淺拷貝和深拷貝
- Python 例外處理
- Python 執行緒創建和傳參
- Python 執行緒互斥鎖 Lock
- Python 執行緒時間 Event
- Python 執行緒條件變數 Condition
- Python 執行緒定時器 Timer
- Python 執行緒信號量 Semaphore
- Python 執行緒障礙物件 Barrier
- Python 執行緒佇列 Queue – FIFO
- Python 執行緒佇列 LifoQueue – LIFO
- Python 執行緒優先佇列 PriorityQueue
- Python 執行緒池 ThreadPoolExecutor(一)
- Python 執行緒池 ThreadPoolExecutor(二)
- Python 行程 Process 模塊
- Python 行程 Process 與執行緒 threading 區別
- Python 行程間通信 Queue / Pipe
未經允許不得轉載:猿說編程 ? Python 行程互斥鎖 Lock
本文由博客 - 猿說編程 猿說編程 發布!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/288757.html
標籤:其他
