并發(fā)與鎖
多個(gè)線程共享數(shù)據(jù)的時(shí)候,如果數(shù)據(jù)不進(jìn)行保護(hù),那么可能出現(xiàn)數(shù)據(jù)不一致現(xiàn)象,使用鎖,信號(hào)量、條件鎖
互斥鎖
1. 互斥鎖,是使用一把鎖把代碼保護(hù)起來,以犧牲性能換取代碼的安全性,那么Rlock后 必須要relase 解鎖 不然將會(huì)失去多線程程序的優(yōu)勢
2. 互斥鎖的基本使用規(guī)則:
import threading
# 聲明互斥鎖
lock=threading.Rlock();
def handle(sid):# 功能實(shí)現(xiàn)代碼
lock.acquire() #加鎖
# writer codeing
lock.relase() #釋放鎖
信號(hào)量:
1. 調(diào)用relarse()信號(hào)量會(huì)+1 調(diào)用 acquire() 信號(hào)量會(huì)-1
可以理解為對(duì)于臨界資源的使用,以及進(jìn)入臨界區(qū)的判斷條件
2. semphore() :當(dāng)調(diào)用relarse()函數(shù)的時(shí)候 單純+1 不會(huì)檢查信號(hào)量的上限情況。 初始參數(shù)為0
3. boudedsemphore():邊界信號(hào)量 當(dāng)調(diào)用relarse() 會(huì)+1 , 并且會(huì)檢查信號(hào)量的上限情況。不允許超過上限
使用budedsemaphore時(shí)候不允許設(shè)置初始為0,將會(huì)拋出異常
至少設(shè)置為1 ,如consumer product 時(shí)候應(yīng)該在外設(shè)置一個(gè)變量,啟動(dòng)時(shí)候?qū)ψ兞孔雠袛啵瑳Q定使不使用acquier
4. 信號(hào)量的基本使用代碼:
# 聲明信號(hào)量:
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
"""
# 信號(hào)量解決生產(chǎn)者消費(fèi)者問題
import random;
import threading;
import time;
# 聲明信號(hào)量
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)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

