溫馨提示×

如何利用NotifyAll實現(xiàn)線程同步

小樊
83
2024-09-03 02:24:50
欄目: 編程語言

NotifyAll 是一種線程同步機(jī)制,用于在多個線程之間進(jìn)行通信和協(xié)作

  1. 導(dǎo)入所需庫:
import threading
import time
  1. 創(chuàng)建一個共享資源類,該類包含一個鎖(Lock)對象和一個條件變量(Condition)對象。這將允許我們在多個線程之間同步對共享資源的訪問。
class SharedResource:
    def __init__(self):
        self.lock = threading.Lock()
        self.condition = threading.Condition(self.lock)
  1. 在共享資源類中添加一些方法來處理共享資源的狀態(tài)更改。例如,我們可以添加一個方法來增加共享資源的值,并在值達(dá)到特定閾值時通知所有等待的線程。
class SharedResource:
    # ... (previous code)

    def increment_value(self):
        with self.condition:
            # Increment the shared resource's value
            self.value += 1

            # Check if the value has reached a specific threshold
            if self.value >= self.threshold:
                # Notify all waiting threads
                self.condition.notify_all()
  1. 創(chuàng)建工作線程類,該類將執(zhí)行特定任務(wù)并與共享資源交互。在此示例中,我們將創(chuàng)建一個線程,當(dāng)共享資源的值達(dá)到閾值時,該線程將執(zhí)行某個操作。
class WorkerThread(threading.Thread):
    def __init__(self, shared_resource):
        super().__init__()
        self.shared_resource = shared_resource

    def run(self):
        with self.shared_resource.condition:
            # Wait until the shared resource's value reaches the threshold
            while self.shared_resource.value< self.shared_resource.threshold:
                self.shared_resource.condition.wait()

            # Perform some action when the condition is met
            print(f"Thread {self.name} is performing an action")
  1. 在主程序中創(chuàng)建共享資源對象、工作線程對象并啟動線程。
def main():
    shared_resource = SharedResource()

    # Create and start worker threads
    worker_threads = [WorkerThread(shared_resource) for _ in range(3)]
    for thread in worker_threads:
        thread.start()

    # Increment the shared resource's value
    for _ in range(10):
        time.sleep(0.5)
        shared_resource.increment_value()

    # Wait for all worker threads to finish
    for thread in worker_threads:
        thread.join()

if __name__ == "__main__":
    main()

在這個示例中,我們使用 NotifyAll 方法通知所有等待的線程,共享資源的值已達(dá)到閾值。這樣,當(dāng)條件滿足時,所有等待的線程都將被喚醒并執(zhí)行相應(yīng)的操作。

0