zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python线程-线程的同步(二)

2023-06-13 09:18:44 时间

条件变量(Condition)

条件变量是一种高级的线程同步机制,它允许线程在某个条件发生变化之前等待,直到条件变为真才被唤醒。在 Python 中,可以使用 threading.Condition 类来创建一个条件变量。条件变量有三个操作:wait()、notify() 和 notify_all()。wait() 方法用于等待条件变量,notify() 方法用于通知等待的线程条件变量已经发生变化,notify_all() 方法用于通知所有等待的线程条件变量已经发生变化。

以下是一个示例,演示了如何使用条件变量来等待和通知线程:

import threading
import time

class Queue:
    """队列类"""

    def __init__(self):
        self._queue = []
        self._condition = threading.Condition()

    def put(self, item):
        """往队列中添加元素"""
        with self._condition:
            self._queue.append(item)
            self._condition.notify()

    def get(self):
        """从队列中取出元素"""
        with self._condition:
            while not self._queue:
                self._condition.wait()
            return self._queue.pop(0)

def producer(queue):
    """生产者线程函数"""
    print("Producer thread started")
    for i in range(5):
        item = "item %d" % i
        print("Producing", item)
        queue.put(item)
        time.sleep(1)
    print("Producer thread finished")

def consumer(queue):
    """消费者线程函数"""
    print("Consumer thread started")
    while True:
        item = queue.get()
        print("Consuming", item)
        time.sleep(1)
    print("Consumer thread finished")

# 创建队列对象
queue = Queue()

# 创建生产者线程
t1 = threading.Thread(target=producer, args=(queue,))

# 创建消费者线程
t2 = threading.Thread(target=consumer, args=(queue,))

# 启动线程
t1.start()
t2.start()

# 等待线程结束
t1.join()
t2.join()

在上面的代码中,我们定义了一个队列类 Queue,它包含一个列表和一个条件变量。然后,我们创建了一个生产者线程和一个消费者线程,并将队列对象作为参数传递给它们的线程函数。生产者线程使用 put() 方法往队列中添加元素,并使用 notify() 方法通知等待的消费者线程条件变量已经发生变化。消费者线程使用 get() 方法从队列中取出元素,并使用 wait() 方法等待条件变量变为真。最后,我们使用 join() 方法等待线程结束。