Python 线程同步与通信机制详解
1. 线程同步基础
在并发编程中,线程同步是一个关键问题。Python 提供了多种同步原语,帮助我们处理线程间的协作和资源竞争。
1.1 发布 - 订阅模型
发布 - 订阅模型是一种常见的线程同步模式。在这个模式中,有一个发布者(Publisher)和多个订阅者(Subscriber)。发布者负责向一个数组(类似于消息队列)中添加数据,而订阅者则从数组中取出数据。
以下是一个简单的发布 - 订阅模型的代码示例:
import threading
class Publisher:
def __init__(self, integers, condition):
self.integers = integers
self.condition = condition
def run(self):
while True:
self.condition.acquire()
print(f"Condition Acquired by Publisher: {threading.current_thread().name}")
num = 108 # 示例数据
self.integers.append(num)
print(f"Publisher {threading.current_thread().name} appending to array: {num}"