多线程编程中的条件变量及其优化

本套课在线学习视频(网盘地址,保存到网盘即可免费观看):

链接:https://pan.quark.cn/s/7220b198cf00

在多线程编程中,条件变量是一种用于线程间通信和同步的机制。通过使用条件变量,可以有效地协调线程间的关系,优化资源利用,并减少线程在CPU资源上的不必要占用。本文将通过Python示例代码,详细介绍如何在多线程环境中使用条件变量。

00:00 - 多线程编程中的条件变量及其优化

使用条件变量优化线程间的协调与资源利用

条件变量允许线程在某个条件不满足时进入等待状态,并在条件满足时被唤醒。这样可以避免线程空闲时对CPU资源的占用,并提高程序性能。

import threading
import time

# 共享资源
shared_data = []
lock = threading.Lock()
condition = threading.Condition(lock)

class Producer(threading.Thread):
    def __init__(self, name):
        super().__init__()
        self.name = name
    
    def run(self):
        global shared_data
        while True:
            with condition:
                shared_data.append(f"Data from {self.name}")
                print(f"{self.name} produced data")
                condition.notify_all()  # 通知所有等待的消费者
            time.sleep(1)

class Consumer(threading.Thread):
    def __init__(self, name):
        super().__init__()
        self.name = name
    
    def run(self):
        global shared_data
        while True:
            with condition:
                while not shared_data:
                    print(f"{self.name} is waiting")
                    condition.wait()  # 等待生产者通知
                data = shared_data.pop(0)
                print(f"{self.name} consumed {data}")
            time.sleep(1)

# 创建生产者和消费者线程
producers = [Producer(f"Producer-{i}") for i in range(2)]
consumers = [Consumer(f"Consumer-{i}") for i in range(3)]

# 启动线程
for producer in producers:
    producer.start()
for consumer in consumers:
    consumer.start()

# 等待线程结束(这里实际上是无限循环,所以不会结束)
for producer in producers:
    producer.join()
for consumer in consumers:
    consumer.join()

02:02 - 条件变量实现生产者-消费者模型

通过引入条件变量,优化了生产者-消费者模型,使得程序在资源不足时能够进入等待状态,并在资源可用时被唤醒继续执行。这种优化方式提高了程序的性能,特别是在资源闲置状态下能够及时释放锁,避免了不必要的阻塞。

import threading
import time
import random

# 共享资源
buffer = []
buffer_size = 5
lock = threading.Lock()
condition = threading.Condition(lock)

class Producer(threading.Thread):
    def __init__(self, name):
        super().__init__()
        self.name = name
    
    def run(self):
        global buffer
        while True:
            with condition:
                while len(buffer) >= buffer_size:
                    print(f"{self.name} is waiting due to full buffer")
                    condition.wait()  # 等待消费者消费
                item = f"Item from {self.name}"
                buffer.append(item)
                print(f"{self.name} produced {item}")
                condition.notify_all()  # 通知所有等待的消费者
            time.sleep(random.random())

class Consumer(threading.Thread):
    def __init__(self, name):
        super().__init__()
        self.name = name
    
    def run(self):
        global buffer
        while True:
            with condition:
                while not buffer:
                    print(f"{self.name} is waiting due to empty buffer")
                    condition.wait()  # 等待生产者生产
                item = buffer.pop(0)
                print(f"{self.name} consumed {item}")
                condition.notify_all()  # 通知所有等待的生产者
            time.sleep(random.random())

# 创建生产者和消费者线程
producers = [Producer(f"Producer-{i}") for i in range(2)]
consumers = [Consumer(f"Consumer-{i}") for i in range(3)]

# 启动线程
for producer in producers:
    producer.start()
for consumer in consumers:
    consumer.start()

# 等待线程结束(这里实际上是无限循环,所以不会结束)
for producer in producers:
    producer.join()
for consumer in consumers:
    consumer.join()

通过这些示例代码,您可以更好地理解如何在Python中使用条件变量来优化多线程编程,特别是在生产者-消费者模型中,条件变量能够显著提高程序的性能和资源利用率。

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-14 16:52:03       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-14 16:52:03       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-14 16:52:03       58 阅读
  4. Python语言-面向对象

    2024-07-14 16:52:03       69 阅读

热门阅读

  1. STM32F103控制0.96寸OLED显示

    2024-07-14 16:52:03       15 阅读
  2. GESP C++ 三级真题(2023年9月)T1 ⼩ 杨储蓄

    2024-07-14 16:52:03       14 阅读
  3. 2024年交安安全员考试题库及答案

    2024-07-14 16:52:03       19 阅读
  4. 2024年高校辅导员考试题库及答案

    2024-07-14 16:52:03       25 阅读
  5. VMM、VMI、VIM的简介

    2024-07-14 16:52:03       16 阅读
  6. Python 面试热门问题五

    2024-07-14 16:52:03       22 阅读
  7. TCP流量控制是怎么实现的?

    2024-07-14 16:52:03       24 阅读
  8. C#开发翻译较好的API

    2024-07-14 16:52:03       19 阅读
  9. C语言西蒙说游戏

    2024-07-14 16:52:03       25 阅读