1. 程式人生 > >Python進階(二十六)-多執行緒實現同步的四種方式

Python進階(二十六)-多執行緒實現同步的四種方式

分享一下我的偶像大神的人工智慧教程!http://blog.csdn.net/jiangjunshow

也歡迎轉載我的文章,轉載請註明出處 https://blog.csdn.net/mm2zzyzzp

Python進階(二十六)-多執行緒實現同步的四種方式

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

鎖機制

  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()#使執行緒一個一個執行
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

  當一個執行緒呼叫鎖的acquire()方法獲得鎖時,鎖就進入“locked”狀態。每次只有一個執行緒可以獲得鎖。如果此時另一個執行緒試圖獲得這個鎖,該執行緒就會變為“blocked”狀態,稱為“同步阻塞”(參見多執行緒的基本概念)。
  直到擁有鎖的執行緒呼叫鎖的release()方法釋放鎖之後,鎖進入“unlocked”狀態。執行緒排程程式從處於同步阻塞狀態的執行緒中選擇一個來獲得鎖,並使得該執行緒進入執行(running)狀態。

訊號量

  訊號量也提供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()
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

條件判斷

  所謂條件變數,即這種機制是在滿足了特定的條件後,執行緒才可以訪問相關的資料。
  它使用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()
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

同步佇列

  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
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38


這裡寫圖片描述

給我偶像的人工智慧教程打call!http://blog.csdn.net/jiangjunshow