多线程竞态

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

单资源竞态

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

  • 产品个数: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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值