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
方法通知所有等待的线程,共享资源的值已达到阈值。这样,当条件满足时,所有等待的线程都将被唤醒并执行相应的操作。