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

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

链接: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中使用条件变量来优化多线程编程,特别是在生产者-消费者模型中,条件变量能够显著提高程序的性能和资源利用率。

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

web安全工具库

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值