目錄
和前面講到的 Python 線程互斥鎖 Lock 類似蔑赘,當有多個進程 Process 同時讀寫同一個文件時痪宰,為了避免數(shù)據(jù)讀寫產生異常弱匪,我們需要為正在操作的進程加上互斥鎖,互斥鎖的原理不管是對線程 threading 還是對進程 Process 而言都是一樣昧狮。
一.Python 線程互斥鎖和進程互斥鎖
1.創(chuàng)建線程互斥鎖
# !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
# 創(chuàng)建線程互斥鎖
mutex = threading.Lock()
2.創(chuàng)建進程互斥鎖
# !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
# 創(chuàng)建進程互斥鎖
mutex = Lock()
注意導入模塊的區(qū)別透葛,不要混淆使用!
二.進程互斥鎖 Lock 函數(shù)介紹
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
'''
重輸出的結果來看,多個進程同時在操作蹄胰,如果是對同一個文件讀寫操作岳遥,很明顯已經亂套了,這并不是我們想要的裕寨;如果多進程在讀寫同一文件時想要保證數(shù)據(jù)安全浩蓉,必然需要加上互斥鎖 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 之后也不會造成數(shù)據(jù)混亂的問題阅悍,同時也提高了效率好渠,完美解決案例一的問題!
案例三:對全局變量累計求和看看計算結果
# !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 函數(shù)中得 num 值怎么會是 0 霍掺,明明主進程/兩個子進程都用關鍵字 **global **聲明了全局變量,即便沒有互斥鎖,也應該是一個小于 20000 的隨機數(shù)杆烁,在文章 Python 進程 Process 與線程 threading 區(qū)別 中有詳細講解牙丽,同一進程的所有線程共享該進程的所有資源,進程與進程之間資源相互獨立兔魂,互不影響(類似深拷貝)烤芦;
上面的程序有三個進程,這就意味著 num 變量實際上有三份資源析校,其中兩個進程對 num 分別做了 10000 次累計加 1 构罗,所以每個子進程的值都是 10000 ,主進程沒有對 num 任何操作智玻,所以主進程 num 值為 0 遂唧;
四.猜你喜歡
- Python 條件推導式
- Python 列表推導式
- Python 字典推導式
- Python 不定長參數(shù) *argc/**kargcs
- Python 匿名函數(shù) lambda
- Python return 邏輯判斷表達式
- Python is 和 == 區(qū)別
- Python 可變數(shù)據(jù)類型和不可變數(shù)據(jù)類型
- Python 淺拷貝和深拷貝
- Python 異常處理
- Python 線程創(chuàng)建和傳參
- Python 線程互斥鎖 Lock
- Python 線程時間 Event
- Python 線程條件變量 Condition
- Python 線程定時器 Timer
- Python 線程信號量 Semaphore
- Python 線程障礙對象 Barrier
- Python 線程隊列 Queue – FIFO
- Python 線程隊列 LifoQueue – LIFO
- Python 線程優(yōu)先隊列 PriorityQueue
- Python 線程池 ThreadPoolExecutor(一)
- Python 線程池 ThreadPoolExecutor(二)
- Python 進程 Process 模塊
- Python 進程 Process 與線程 threading 區(qū)別
- Python 進程間通信 Queue / Pipe
未經允許不得轉載:猿說編程 ? Python 進程互斥鎖 Lock
本文由博客 - 猿說編程 猿說編程 發(fā)布!