在python中使用wait()函数实现线程的阻塞和唤醒
发布时间:2024-01-02 15:39:55
在Python中,我们可以使用wait()函数实现线程的阻塞和唤醒。wait()函数会使当前线程进入等待状态,并释放对共享资源的所有权,直到被其他线程调用notify()或notify_all()函数唤醒。
下面是一个使用wait()函数实现线程阻塞和唤醒的例子:
import threading
# 共享资源
shared_resource = []
# 创建一个条件变量对象
cv = threading.Condition()
# 生产者线程函数
def producer():
global shared_resource
# 获取条件变量的锁
with cv:
# 如果共享资源不为空,则等待
while shared_resource:
print("Producer is waiting...")
cv.wait()
# 生产一个数据并添加到共享资源中
data = "New Data"
shared_resource.append(data)
print("Producer produces:", data)
# 唤醒等待的消费者线程
cv.notify()
# 消费者线程函数
def consumer():
global shared_resource
# 获取条件变量的锁
with cv:
# 如果共享资源为空,则等待
while not shared_resource:
print("Consumer is waiting...")
cv.wait()
# 从共享资源中消费一个数据
data = shared_resource.pop()
print("Consumer consumes:", data)
# 唤醒等待的生产者线程
cv.notify()
# 创建生产者线程和消费者线程
producer_thread = threading.Thread(target=producer)
consumer_thread = threading.Thread(target=consumer)
# 启动线程
producer_thread.start()
consumer_thread.start()
# 等待线程执行完成
producer_thread.join()
consumer_thread.join()
在上面的例子中,我们使用threading.Condition()创建了一个条件变量对象cv,并通过cv.wait()实现了线程的阻塞。生产者线程调用cv.notify()唤醒等待的消费者线程,消费者线程调用cv.notify()唤醒等待的生产者线程。
当运行上面的代码时,我们会看到生产者和消费者线程交替执行,生产者先生产一个数据,然后消费者消费该数据,然后再生产下一个数据,消费者再次消费,如此循环。在每次生产或消费之前,线程会通过cv.wait()进入等待状态,等待其他线程的唤醒。
