日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python 进程互斥锁 Lock - Python零基础入门教程

發布時間:2024/9/27 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 进程互斥锁 Lock - Python零基础入门教程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

  • 一.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 osdef 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 osdef 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,Locknum = 0def get_sum1():global num # 聲明全局變量for i in range(10000):num = num +1print("get_sum1:",num)def get_sum2():global num # 聲明全局變量for i in range(10000):num = num + 1print("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

    總結

    以上是生活随笔為你收集整理的Python 进程互斥锁 Lock - Python零基础入门教程的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。