Python的互斥鎖與信號量詳解
并發(fā)與鎖
多個線程共享數(shù)據(jù)的時候,如果數(shù)據(jù)不進(jìn)行保護(hù),那么可能出現(xiàn)數(shù)據(jù)不一致現(xiàn)象,使用鎖,信號量、條件鎖
互斥鎖
1. 互斥鎖,是使用一把鎖把代碼保護(hù)起來,以犧牲性能換取代碼的安全性,那么Rlock后 必須要relase 解鎖 不然將會失去多線程程序的優(yōu)勢
2. 互斥鎖的基本使用規(guī)則:
import threading # 聲明互斥鎖 lock=threading.Rlock(); def handle(sid):# 功能實(shí)現(xiàn)代碼 lock.acquire() #加鎖 # writer codeing lock.relase() #釋放鎖
信號量:
1. 調(diào)用relarse()信號量會+1 調(diào)用 acquire() 信號量會-1
可以理解為對于臨界資源的使用,以及進(jìn)入臨界區(qū)的判斷條件
2. semphore() :當(dāng)調(diào)用relarse()函數(shù)的時候 單純+1 不會檢查信號量的上限情況。 初始參數(shù)為0
3. boudedsemphore():邊界信號量 當(dāng)調(diào)用relarse() 會+1 , 并且會檢查信號量的上限情況。不允許超過上限
使用budedsemaphore時候不允許設(shè)置初始為0,將會拋出異常
至少設(shè)置為1 ,如consumer product 時候應(yīng)該在外設(shè)置一個變量,啟動時候?qū)ψ兞孔雠袛?,決定使不使用acquier
4. 信號量的基本使用代碼:
# 聲明信號量:
sema=threading.Semaphore(0); #無上限檢查
sema=threading.BuderedSeamphore(1) #有上限檢查設(shè)置
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("消費(fèi):",apple);
全部的代碼:
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 9 21:49:30 2019
@author: DGW-PC
"""
# 信號量解決生產(chǎn)者消費(fèi)者問題
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("消費(fèi):",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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python PIL中ImageFilter模塊圖片濾波處理和使用方法
這篇文章主要介紹PIL中ImageFilter模塊幾種圖片濾波處理和使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-11-11
使用selenium+chromedriver+xpath爬取動態(tài)加載信息
這篇文章主要介紹了使用selenium+chromedriver+xpath爬取動態(tài)加載信息2022-02-02
python利用pytesseract 實(shí)現(xiàn)本地識別圖片文字
這篇文章主要介紹了python利用pytesseract 實(shí)現(xiàn)本地識別圖片文字,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12
PyTorch實(shí)現(xiàn)線性回歸詳細(xì)過程
本文介紹PyTorch實(shí)現(xiàn)線性回歸,線性關(guān)系是一種非常簡單的變量之間的關(guān)系,因變量和自變量在線性關(guān)系的情況下,可以使用線性回歸算法對一個或多個因變量和自變量間的線性關(guān)系進(jìn)行建模,該模型的系數(shù)可以用最小二乘法進(jìn)行求解,需要的朋友可以參考一下2022-03-03
Python?OpenCV形態(tài)學(xué)運(yùn)算示例詳解
這篇文章主要為大家介紹了OpenCV中的幾個形態(tài)學(xué)運(yùn)算,例如:腐蝕&膨脹、開&閉運(yùn)算、梯度運(yùn)算、頂帽運(yùn)算黑帽運(yùn)算,感興趣的可以了解一下2022-04-04

