臨界資源即那些一次只能被一個線程訪問的資源,典型例子就是打印機,它一次只能被一個程序用來執行打印功能,因為不能多個線程同時操作,而訪問這部分資源的代碼通常稱之為臨界區。
鎖機制
threading的Lock類,用該類的acquire函數進行加鎖,用realease函數進行解鎖
import threadingimport timeclass 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 numn = 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)狀態。
信號量
信號量也提供acquire方法和release方法,每當調用acquire方法的時候,如果內部計數器大于0,則將其減1,如果內部計數器等于0,則會阻塞該線程,知道有線程調用了release方法將內部計數器更新到大于1位置。
import threadingimport timeclass 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 numn = 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()
條件判斷
所謂條件變量,即這種機制是在滿足了特定的條件后,線程才可以訪問相關的數據。 
它使用Condition類來完成,由于它也可以像鎖機制那樣用,所以它也有acquire方法和release方法,而且它還有wait,notify,notifyAll方法。
"""一個簡單的生產消費者模型,通過條件變量的控制產品數量的增減,調用一次生產者產品就是+1,調用一次消費者產品就會-1.""""""使用 Condition 類來完成,由于它也可以像鎖機制那樣用,所以它也有 acquire 方法和 release 方法,而且它還有wait, notify, notifyAll 方法。"""import threadingimport queue,time,randomclass 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 <= 0class 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()            
新聞熱點
疑難解答