并發與鎖
多個線程共享數據的時候,如果數據不進行保護,那么可能出現數據不一致現象,使用鎖,信號量、條件鎖
互斥鎖
1. 互斥鎖,是使用一把鎖把代碼保護起來,以犧牲性能換取代碼的安全性,那么Rlock后 必須要relase 解鎖 不然將會失去多線程程序的優勢
2. 互斥鎖的基本使用規則:
import threading # 聲明互斥鎖 lock=threading.Rlock(); def handle(sid):# 功能實現代碼 lock.acquire() #加鎖 # writer codeing lock.relase() #釋放鎖
信號量:
1. 調用relarse()信號量會+1 調用 acquire() 信號量會-1
可以理解為對于臨界資源的使用,以及進入臨界區的判斷條件
2. semphore() :當調用relarse()函數的時候 單純+1 不會檢查信號量的上限情況。 初始參數為0
3. boudedsemphore():邊界信號量 當調用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 """ # 信號量解決生產者消費者問題 import random; import threading; import time; # 聲明信號量 sema=threading.Semaphore(0);# 必須寫參數 0 表示可以使用數 sema2=threading.BoundedSemaphore(1); apple=1; def product():#生產者 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();
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
