多线程竞态

多线程竞态,是指的多个线程同时访问/修改共享资源时,出现不可预知的结果。

单资源竞态

我们引入典型的生产者-消费者的场景:

  • 产品个数:productCount;
  • 生产者:生产1个产品,产品个数增加1;
  • 消费者:消费1个产品,产品个数减去1。

其具体代码(C++)如下所示:

#include <cstdint>
#include <functional>
#include <iostream>
#include <thread>

using namespace std;

// 共享资源:产品个数
int32_t productCount = 0;

// 生产者:生产
void Produce()
{
    productCount += 1;
}

// 消费者:消费
void Consume()
{
    productCount -= 1;
}

// 创建两个线程,分别充当生产者和消费者
void ChangeProductCount(uint32_t runCount)
{
    auto run = [=](function<void()> action) {
        for (uint32_t i = 0; i < runCount; ++i) {
            action();
        }
    };

    thread producer(run, Produce);
    thread consumer(run, Consume);

    this_thread::sleep_for(chrono::milliseconds(1));

    producer.join();
    consumer.join();
}

int main()
{
    ChangeProductCount(100);

    cout << productCount << endl;

    return 0;
}

上述代码,我们期望的结果应该是0,而且实际测试结果中大多数情况下都是0。该如何理解这个大多数呢?而且我也很好奇,这个运行结果应该是怎样的一个分布情况呢?

于是,我对上述代码main函数进行了一次改造,将实际多线程的函数运行了10000次。

/****************改造升级运行10000次,并统计结果值的分布************************/
void Statistic()
{
    map<int32_t, int32_t> resultCount; 
    for (int32_t i = 0; i < 10000; ++i) {
        productCount = 0; // 每次运行多线程前清零,避免干扰
        ChangeProductCount(100);
        resultCount[productCount]++;
    }

    for (auto& item : resultCount) {
        cout << item.first << " " << item.second << endl;
    }
}

int main()
{
    Statistic();

    return 0;
}

其运行结果统计信息如下图所示:

单变量竞态运行统计

从上图可以很直观的看出来,这个所谓的大多数情况都是符合期望值0,只有少数不符合期望。正是由于我们所谓的大多数情况下都是正确的,就给我们大家造成一种“以前都是正确的,又没有改任何代码,怎么是我的代码造成的呢?”的错觉。

单资源竞态原因

其实,我们对一个变量运算,大体分为3个步骤,从内存读取到CPU、CPU计算、从CPU写回内存。一个线程完全没有问题,但是多线程情况下就有所不同了,比如下标所示,productCount默认值为0:

时间序列producer线程consumer线程
1读取值0
2读取值0计算:0 - 1 = -1
3计算:0 + 1 = 1写回:-1
4写回:1

从上表可以看出2个问题:

  • 生产1次,消费1次,结果却是1;
  • 还没有产品,消费者却在消费。——此问题,不在此处的讨论范畴内。

单资源竞态解决方案

因为上述的三个步骤,不是一个原子步骤,就让多线程有机可乘。如果我们能保证上述3个步骤能在一个原子动作内完成即可保证最终结果符合期望了。

在上述代码中,将 productCount 改成一个原子变量即可。修改方法如下:

#include <atomic>  // 增加原子头文件

atomic_int32_t productCount{0};  // 将原来普通变量,改为原子变量即可。

运行结果如下:

单资源竞态-原子变量

多资源竞态

如果在生产者-消费者场景中,增加单个产品的价格,考虑最终的收益:

  • 产品个数:productCount;产品收益:productIncome;
  • 生产者:生产1个产品,产品个数增加1,收益减少10;
  • 消费者:消费1个产品,产品个数减去1,收益增加20。

其具体代码如下所示:

#include <atomic>
#include <cstdint>
#include <functional>
#include <iostream>
#include <map>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

using namespace std;

// 打印互斥锁
mutex recordMtx;
vector<string> runInfos;

// 共享资源:产品个数,产品收益
atomic_int32_t productCount{0};
atomic_int32_t productIncome{0};

void Record(const string& name)
{
    lock_guard<mutex> guard(recordMtx);
    runInfos.push_back(name + " productCount:" + to_string(productCount) + " income:" + to_string(productIncome));
}

// 生产者:生产
void Produce()
{
    productCount += 1;
    productIncome -= 10;

    Record("producer");
}

// 消费者:消费
void Consume()
{
    productCount -= 1;
    productIncome += 20;

    Record("consumer");
}

// 创建两个线程,分别充当生产者和消费者
void ChangeProductCount(uint32_t runCount)
{
    auto run = [=](function<void()> action) {
        for (uint32_t i = 0; i < runCount; ++i) {
            action();
        }
    };

    thread producer(run, Produce);
    thread consumer(run, Consume);

    this_thread::sleep_for(chrono::milliseconds(1));

    producer.join();
    consumer.join();
}

int main()
{
    ChangeProductCount(5);

    for (auto& info : runInfos) {
        cout << info << endl;
    }

    return 0;
}

运行结果如下:

producer productCount:1 income:-10
producer productCount:1 income:0
consumer productCount:2 income:0
consumer productCount:1 income:10
consumer productCount:0 income:30
consumer productCount:-1 income:50
consumer productCount:-2 income:70
producer productCount:-2 income:70
producer productCount:-1 income:60
producer productCount:0 income:50

上述代码例子中,借鉴了前面的例子,采用了原子变量的方式。虽说,运行结果符合期望,但是在运行过程中,是存在问题的,比如第3行,是生产者打印了2次,消费者打印1次,表示已经生产了2个消费1个,收入为0。但是,产品数量为2,收入却为0。

多资源竞态原因

虽说单个变量已经保证了读取、计算、写回这三个动作作为一个原子动作,但是多个变量的之间的联动未保持一致。如下表所示:

时间序列生产者-产品个数生产者-收入消费者-产品个数消费者-收入产品个数收益
1生产:1收益:-101-10
2生产:1收益:-10消费:1收益:+2010
3生产:120
4收益:-102-10

多资源竞态解决方案:

加锁保护多资源,保证相关的多资源操作是一个原子的操作,避免某一个资源正在被操作时,被其他线程操作另外一个资源。因此,修改方法如下所示(不考虑仅有产品时,消费者才消费的场景):

#include <cstdint>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

using namespace std;

// 资源互斥锁
mutex resMtx;
vector<string> runInfos;

// 共享资源:产品个数,产品收益
int32_t productCount{0};
int32_t productIncome{0};

void Record(const string& name)
{
    runInfos.push_back(name + " productCount:" + to_string(productCount) + " income:" + to_string(productIncome));
}

// 生产者:生产
void Produce()
{
    lock_guard<mutex> guard(resMtx);

    productCount += 1;
    productIncome -= 10;

    Record("producer");
}

// 消费者:消费
void Consume()
{
    lock_guard<mutex> guard(resMtx);

    productCount -= 1;
    productIncome += 20;

    Record("consumer");
}

// 创建两个线程,分别充当生产者和消费者
void ChangeProductCount(uint32_t runCount)
{
    auto run = [=](function<void()> action) {
        for (uint32_t i = 0; i < runCount; ++i) {
            action();
        }
    };

    thread producer(run, Produce);
    thread consumer(run, Consume);

    this_thread::sleep_for(chrono::milliseconds(1));

    producer.join();
    consumer.join();
}

int main()
{
    ChangeProductCount(5);

    for (auto& info : runInfos) {
        cout << info << endl;
    }

    return 0;
}

其运行结果如下:

producer productCount:1 income:-10
producer productCount:2 income:-20
producer productCount:3 income:-30
producer productCount:4 income:-40
producer productCount:5 income:-50
consumer productCount:4 income:-30
consumer productCount:3 income:-10
consumer productCount:2 income:10
consumer productCount:1 income:30
consumer productCount:0 income:50
<think>嗯,用户让我解释多线程条件、临界区这三个概念。首先,我需要确保自己正确理解每个术语的定义,然后考虑如何用中文清晰、有条理地解释它们。可能需要从基础开始,逐步深入,让用户能够一步步理解这些概念之间的关系。 首先,多线程多线程是指一个程序中有多个线程同时执行,共享同一进程的资源。线程是轻量级的执行单元,多线程可以提高程序的效率,尤其是在多核CPU上。但用户可能已经知道这些,所以需要简洁说明,重点放在为什么需要多线程以及它带来的好处和问题。 接下来是条件。当多个线程访问共享资源时,如果没有适当的同步,执行顺序的不确定性可能导致结果不一致,这就是条件。需要举一个例子,比如两个线程同时增加一个计数器,如果不加控制,最终结果可能不正确。这个例子比较经典,用户可能容易理解。 然后是临界区。临界区是代码中访问共享资源的部分,必须确保同一时间只有一个线程执行这部分代码。临界区的概念是为了解决条件问题,所以需要说明如何通过同步机制(如锁)来保护临界区,防止多个线程同时进入。 用户可能还想知道这三个概念之间的联系,比如多线程导致条件,而临界区用来解决这个问题。需要强调同步机制的重要性,以及不同同步方法(如互斥锁、信号量)的简要区别。 另外,用户可能对这些概念的实际应用场景或常见问题感兴趣。比如,在Web服务器处理多个请求时,如何避免条件。或者,在数据库事务中如何使用锁来保护临界区。不过,可能不需要太深入,保持解释的简洁性。 需要检查是否有术语使用不当,比如“临界区”是否还有其他名称,比如“关键区”,但通常“临界区”更常见。还要确保例子中的代码或场景正确,比如两个线程同时修改同一个变量,导致结果不符合预期。 最后,确保结构清晰,分点解释每个概念,然后总结它们之间的关系。可能还需要提到死锁或其他相关问题,但用户的问题没有提到,所以可能不需要展开。总之,保持回答准确、易懂,符合用户的要求。</think>好的,我将逐步解释这三个关键概念及其关系: 1. **多线程 (Multithreading)** $$线程 = 程序执行的独立路径$$ - 多线程允许单个进程同时执行多个任务流 - 优势:提高CPU利用率、响应速度更快 - 示例:浏览器同时加载网页、播放音乐和处理用户输入 2. **条件 (Race Condition)** $$结果 = f(线程执行顺序)$$ - 当多个线程访问共享资源时,由于执行顺序不可预测导致结果异常 - 典型场景:两个线程同时修改同一变量 - 示例代码: ```python counter = 0 # 线程A:执行 counter +=1 的机器指令被中断 # 线程B:同时执行 counter +=1 # 最终结果可能不是预期的+2 ``` 3. **临界区 (Critical Section)** $$\exists \text{ 锁 } L, \forall \text{ 线程 } T_i: T_i \text{ 需获取 } L \text{ 才能进入临界区}$$ - 定义:访问共享资源的代码段 - 解决方法:通过互斥锁(mutex)、信号量(semaphore)等同步机制 - 正确使用示例: ```python lock = threading.Lock() def safe_increment(): with lock: # 进入临界区 global counter counter +=1 ``` **关系总结**: 多线程编程 → 可能引发条件 → 通过保护临界区解决 → 最终实现线程安全 **补充说明**: - 当线程进入临界区时,系统保证其操作的原子性 - 同步机制的选择会影响性能(如自旋锁 vs 阻塞锁) - 错误处理不当可能引发死锁:$$线程A持有锁L1请求L2 \parallel 线程B持有锁L2请求L1$$
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值