python3.4多線程實現同步的四種方式


臨界資源即那些一次只能被一個線程訪問的資源,典型例子就是打印機,它一次只能被一個程序用來執行打印功能,因為不能多個線程同時操作,而訪問這部分資源的代碼通常稱之為臨界區。

1. 鎖機制

threading的Lock類,用該類的acquire函數進行加鎖,用realease函數進行解鎖

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)狀態。

 

2. 信號量

信號量也提供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. 條件判斷

所謂條件變量,即這種機制是在滿足了特定的條件后,線程才可以訪問相關的數據。

它使用Condition類來完成,由於它也可以像鎖機制那樣用,所以它也有acquire方法和release方法,而且它還有wait,notify,notifyAll方法。

"""
一個簡單的生產消費者模型,通過條件變量的控制產品數量的增減,調用一次生產者產品就是+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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM