臨界資源即那些一次只能被一個線程訪問的資源,典型例子就是打印機,它一次只能被一個程序用來執行打印功能,由於不能多個線程同時操做,而訪問這部分資源的代碼一般稱之爲臨界區。html
1. 鎖機制多線程
threading的Lock類,用該類的acquire函數進行加鎖,用realease函數進行解鎖dom
import threading import time class Num: def __init__(self): self.num = 0 self.lock = threading.Lock() def add(self): self.lock.acquire()#加鎖,鎖住相應的資源 self.num += 1 num = self.num self.lock.release()#解鎖,離開該資源 return num n = Num() class jdThread(threading.Thread): def __init__(self,item): threading.Thread.__init__(self) self.item = item def run(self): time.sleep(2) value = n.add()#將num加1,並輸出原來的數據和+1以後的數據 print(self.item,value) for item in range(5): t = jdThread(item) t.start() t.join()#使線程一個一個執行
當一個線程調用鎖的acquire()方法得到鎖時,鎖就進入「locked」狀態。每次只有一個線程能夠得到鎖。若是此時另外一個線程試圖得到這個鎖,該線程就會變爲「blocked」狀態,稱爲「同步阻塞」(參見多線程的基本概念)。函數
直到擁有鎖的線程調用鎖的release()方法釋放鎖以後,鎖進入「unlocked」狀態。線程調度程序從處於同步阻塞狀態的線程中選擇一個來得到鎖,並使得該線程進入運行(running)狀態。ui
2. 信號量spa
信號量也提供acquire方法和release方法,每當調用acquire方法的時候,若是內部計數器大於0,則將其減1,若是內部計數器等於0,則會阻塞該線程,知道有線程調用了release方法將內部計數器更新到大於1位置。線程
import threading import time class Num: def __init__(self): self.num = 0 self.sem = threading.Semaphore(value = 3) #容許最多三個線程同時訪問資源 def add(self): self.sem.acquire()#內部計數器減1 self.num += 1 num = self.num self.sem.release()#內部計數器加1 return num n = Num() class jdThread(threading.Thread): def __init__(self,item): threading.Thread.__init__(self) self.item = item def run(self): time.sleep(2) value = n.add() print(self.item,value) for item in range(100): t = jdThread(item) t.start() t.join()
3. 條件判斷code
所謂條件變量,即這種機制是在知足了特定的條件後,線程才能夠訪問相關的數據。htm
它使用Condition類來完成,因爲它也能夠像鎖機制那樣用,因此它也有acquire方法和release方法,並且它還有wait,notify,notifyAll方法。blog
""" 一個簡單的生產消費者模型,經過條件變量的控制產品數量的增減,調用一次生產者產品就是+1,調用一次消費者產品就會-1. """ """ 使用 Condition 類來完成,因爲它也能夠像鎖機制那樣用,因此它也有 acquire 方法和 release 方法,並且它還有 wait, notify, notifyAll 方法。 """ import threading import queue,time,random class Goods:#產品類 def __init__(self): self.count = 0 def add(self,num = 1): self.count += num def sub(self): if self.count>=0: self.count -= 1 def empty(self): return self.count <= 0 class Producer(threading.Thread):#生產者類 def __init__(self,condition,goods,sleeptime = 1):#sleeptime=1 threading.Thread.__init__(self) self.cond = condition self.goods = goods self.sleeptime = sleeptime def run(self): cond = self.cond goods = self.goods while True: cond.acquire()#鎖住資源 goods.add() print("產品數量:",goods.count,"生產者線程") cond.notifyAll()#喚醒全部等待的線程--》其實就是喚醒消費者進程 cond.release()#解鎖資源 time.sleep(self.sleeptime) class Consumer(threading.Thread):#消費者類 def __init__(self,condition,goods,sleeptime = 2):#sleeptime=2 threading.Thread.__init__(self) self.cond = condition self.goods = goods self.sleeptime = sleeptime def run(self): cond = self.cond goods = self.goods while True: time.sleep(self.sleeptime) cond.acquire()#鎖住資源 while goods.empty():#如無產品則讓線程等待 cond.wait() goods.sub() print("產品數量:",goods.count,"消費者線程") cond.release()#解鎖資源 g = Goods() c = threading.Condition() pro = Producer(c,g) pro.start() con = Consumer(c,g) con.start()
4. 同步隊列
put方法和task_done方法,queue有一個未完成任務數量num,put依次num+1,task依次num-1.任務都完成時任務結束。
import threading import queue import time import random ''' 1.建立一個 Queue.Queue() 的實例,而後使用數據對它進行填充。 2.將通過填充數據的實例傳遞給線程類,後者是經過繼承 threading.Thread 的方式建立的。 3.每次從隊列中取出一個項目,並使用該線程中的數據和 run 方法以執行相應的工做。 4.在完成這項工做以後,使用 queue.task_done() 函數向任務已經完成的隊列發送一個信號。 5.對隊列執行 join 操做,實際上意味着等到隊列爲空,再退出主程序。 ''' class jdThread(threading.Thread): def __init__(self,index,queue): threading.Thread.__init__(self) self.index = index self.queue = queue def run(self): while True: time.sleep(1) item = self.queue.get() if item is None: break print("序號:",self.index,"任務",item,"完成") self.queue.task_done()#task_done方法使得未完成的任務數量-1 q = queue.Queue(0) ''' 初始化函數接受一個數字來做爲該隊列的容量,若是傳遞的是 一個小於等於0的數,那麼默認會認爲該隊列的容量是無限的. ''' for i in range(2): jdThread(i,q).start()#兩個線程同時完成任務 for i in range(10): q.put(i)#put方法使得未完成的任務數量+1