小编joy*_*tic的帖子

ThreadSanitizer检测到数据争用,问题出在哪里?

在此示例程序中,我试图避免利用lambda函数(称为data_race)来使用前向声明和循环依赖关系

struct B{
    int x;
    std::thread* tid;

    B(int _x){
        x = _x;
        tid = NULL;
    }

    ~B(){
        if(tid != NULL) delete tid;
    }

    void run(std::function<void(B*)> f){
        auto body = [&f, this](){
            f(this);
        };

        tid=new std::thread(body);
    }

    void wait(){
        tid->join();
    }
};

struct A{
    int x;
    std::mutex mtx;

    A(int _x){
        x = _x;
    }

    void foo(B* b){
        std::unique_lock<std::mutex> lock(mtx);
        x = b->x;
    };
};

int main(){
    A a(99);
    std::vector<B> v;

    auto data_race = [&a](B* b){ a.foo(b);};

    for(int i=0; i<10; i++){
        v.push_back(B(i)); …
Run Code Online (Sandbox Code Playgroud)

c++ concurrency multithreading c++11 data-race

0
推荐指数
1
解决办法
83
查看次数

标签 统计

c++ ×1

c++11 ×1

concurrency ×1

data-race ×1

multithreading ×1