NotifyAll
是一種線程同步機制,用于在多個線程之間進行通信和協作
import threading
import time
class SharedResource:
def __init__(self):
self.lock = threading.Lock()
self.condition = threading.Condition(self.lock)
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()
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")
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
方法通知所有等待的線程,共享資源的值已達到閾值。這樣,當條件滿足時,所有等待的線程都將被喚醒并執行相應的操作。