Python的互斥鎖與信號量詳解
并發(fā)與鎖
多個線程共享數(shù)據(jù)的時候,如果數(shù)據(jù)不進行保護,那么可能出現(xiàn)數(shù)據(jù)不一致現(xiàn)象,使用鎖,信號量、條件鎖
互斥鎖
1. 互斥鎖,是使用一把鎖把代碼保護起來,以犧牲性能換取代碼的安全性,那么Rlock后 必須要relase 解鎖 不然將會失去多線程程序的優(yōu)勢
2. 互斥鎖的基本使用規(guī)則:
import threading # 聲明互斥鎖 lock=threading.Rlock(); def handle(sid):# 功能實現(xiàn)代碼 lock.acquire() #加鎖 # writer codeing lock.relase() #釋放鎖
信號量:
1. 調(diào)用relarse()信號量會+1 調(diào)用 acquire() 信號量會-1
可以理解為對于臨界資源的使用,以及進入臨界區(qū)的判斷條件
2. semphore() :當調(diào)用relarse()函數(shù)的時候 單純+1 不會檢查信號量的上限情況。 初始參數(shù)為0
3. boudedsemphore():邊界信號量 當調(diào)用relarse() 會+1 , 并且會檢查信號量的上限情況。不允許超過上限
使用budedsemaphore時候不允許設置初始為0,將會拋出異常
至少設置為1 ,如consumer product 時候應該在外設置一個變量,啟動時候對變量做判斷,決定使不使用acquier
4. 信號量的基本使用代碼:
# 聲明信號量: sema=threading.Semaphore(0); #無上限檢查 sema=threading.BuderedSeamphore(1) #有上限檢查設置 5 apple=1 def consumner(): seam.acquire(); # ‐1 9 if apple==1: pass else: sema2.release();#+ 1 def product(): seam.relarse(); # +1 if apple==1: pass else: print("消費:",apple);
全部的代碼:
# -*- coding: utf-8 -*- """ Created on Mon Sep 9 21:49:30 2019 @author: DGW-PC """ # 信號量解決生產(chǎn)者消費者問題 import random; import threading; import time; # 聲明信號量 sema=threading.Semaphore(0);# 必須寫參數(shù) 0 表示可以使用數(shù) sema2=threading.BoundedSemaphore(1); apple=1; def product():#生產(chǎn)者 global apple; apple=random.randint(1,100); time.sleep(3); print("生成蘋果:",apple); #sema2.release(); # +1 if apple==1: pass else: sema2.release();#+ 1 def consumer(): print("等待"); sema2.acquire();# -1 if apple==1: pass else: print("消費:",apple); threads=[]; for i in range(1,3): t1=threading.Thread(target=consumer); t2=threading.Thread(target=product); t1.start(); t2.start(); threads.append(t1); threads.append(t2); for x in threads: x.join();
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
python PIL中ImageFilter模塊圖片濾波處理和使用方法
這篇文章主要介紹PIL中ImageFilter模塊幾種圖片濾波處理和使用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-11-11使用selenium+chromedriver+xpath爬取動態(tài)加載信息
這篇文章主要介紹了使用selenium+chromedriver+xpath爬取動態(tài)加載信息2022-02-02python利用pytesseract 實現(xiàn)本地識別圖片文字
這篇文章主要介紹了python利用pytesseract 實現(xiàn)本地識別圖片文字,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12