【C++】线程安全问题

原子类型非线程安全

#include 
#include 

int main() {
    int num = 0;

    int count = 100000;

    std::thread thread1([&](){
        for(int i = 0; i < count; i++){
            num++;
        }
    });

    std::thread thread2([&](){

        for(int i = 0; i < count; i++){
            num++;
        }
    });

    std::thread thread3([&](){
        for(int i = 0; i < count; i++){
            num++;
        }
    });

    std::thread thread4([&](){

        for(int i = 0; i < count; i++){
            num++;
        }
    });

    thread1.join();
    thread2.join();
    thread3.join();
    thread4.join();

    std::cout << "num: " << num << std::endl;

    return 0;
}

预期结果
400000

实际结果
在这里插入图片描述

线程安全代码

atomic

#include 
#include 
#include 

int main() {
    std::atomic<int> num(0);

    int count = 100000;

    std::thread thread1([&](){
        for(int i = 0; i < count; i++){
            num++;
        }
    });

    std::thread thread2([&](){

        for(int i = 0; i < count; i++){
            num++;
        }
    });

    std::thread thread3([&](){
        for(int i = 0; i < count; i++){
            num++;
        }
    });

    std::thread thread4([&](){

        for(int i = 0; i < count; i++){
            num++;
        }
    });

    thread1.join();
    thread2.join();
    thread3.join();
    thread4.join();

    std::cout << "num: " << num << std::endl;

    return 0;
}

std::mutex

#include 
#include 
#include 

class Num{
public:
    Num(){
        num = 0;
    }
    void add(){
        std::lock_guard<std::mutex> lock(mtx);
        num++;
    }

    int getNum(){
        std::lock_guard<std::mutex> lock(mtx);
        return num;
    }
private:
    int num;
    std::mutex mtx;
};

int main() {

    Num num;

    int count = 100000;

    std::thread thread1([&](){
        for(int i = 0; i < count; i++){
            num.add();
        }
    });

    std::thread thread2([&](){

        for(int i = 0; i < count; i++){
            num.add();
        }
    });

    std::thread thread3([&](){
        for(int i = 0; i < count; i++){
            num.add();
        }
    });

    std::thread thread4([&](){

        for(int i = 0; i < count; i++){
            num.add();
        }
    });

    thread1.join();
    thread2.join();
    thread3.join();
    thread4.join();

    std::cout << "num: " << num.getNum() << std::endl;

    return 0;
}

你可能感兴趣的:(C/C++,c++,开发语言,算法)