1. 程式人生 > >條件變量同步 -- Condition

條件變量同步 -- Condition

sel pen left png produce join port ima let

  • Python提供的Condition對象提供了對復雜線程同步問題的支持。Condition被稱為條件變量,除了提供與Lock類似的acquire和release方法外,還提供了wait和notify方法。線程首先acquire一個條件變量,然後判斷一些條件。如果條件不滿足則wait;如果條件滿足,進行一些處理改變條件後,通過notify方法通知其他線程,其他處於wait狀態的線程接到通知後會重新判斷條件。不斷的重復這一過程,從而解決復雜的同步問題。

技術分享圖片

上圖中def_A和def_B兩個方法是相互依賴的,描述了A、B兩個方法同步工作的過程

  • 生產者和消費者代碼示例 -- 以下代碼只有消費者依賴了生產者
import threading,time
from random import randint
class Producer(threading.Thread):
    def run(self):
        global L
        while True:
            val = randint(0, 100)
            print(‘生產者‘, self.name, ":Append"+str(val), L)
            if lock_con.acquire():
                L.append(val)
                lock_con.notify()
                lock_con.release()
            time.sleep(3)

class Consumer(threading.Thread):
    def run(self):
        global L
        while True:
                lock_con.acquire()
                if len(L) == 0:
                    lock_con.wait()
                print(‘消費者‘, self.name, ":Delete"+str(L[0]), L)
                del L[0]
                lock_con.release()
                time.sleep(0.25)

if __name__ == "__main__":

    L = []
    lock_con = threading.Condition()
    threads = []
    for i in range(5):
        threads.append(Producer())
    threads.append(Consumer())
    for t in threads:
        t.start()
    for t in threads:
        t.join()

條件變量同步 -- Condition