阅读量:143
NotifyAll 是一种线程同步机制,用于在多个线程之间进行通信和协作
- 导入所需库:
import threading
import time
- 创建一个共享资源类,该类包含一个锁(Lock)对象和一个条件变量(Condition)对象。这将允许我们在多个线程之间同步对共享资源的访问。
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 class="hljs-comment"># 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 方法通知所有等待的线程,共享资源的值已达到阈值。这样,当条件满足时,所有等待的线程都将被唤醒并执行相应的操作。