繁体   English   中英

创建不带锁的thread_safe shared_ptr的正确方法?

[英]Correct way to create thread_safe shared_ptr without a lock?

我正在尝试使用线程安全的shared_ptr创建一个类。 我的用例是shared_ptr属于该类的一个对象,其行为类似于单例(CreateIfNotExist函数可以在任何时间由任何线程运行)。

本质上,如果指针为null,则设置其值的第一个线程将获胜,而同时创建它的所有其他线程将使用获胜线程的值。

这是我到目前为止的内容(请注意,唯一有问题的函数是CreateIfNotExist()函数,其余的只是出于测试目的):

#include <memory>
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>

struct A {
    A(int a) : x(a) {}
    int x;
};

struct B {
    B() : test(nullptr) {}

    void CreateIfNotExist(int val) {
        std::shared_ptr<A> newPtr = std::make_shared<A>(val);
        std::shared_ptr<A> _null = nullptr;
        std::atomic_compare_exchange_strong(&test, &_null, newPtr);
    }

    std::shared_ptr<A> test;
};

int gRet = -1;
std::mutex m;

void Func(B* b, int val) {
    b->CreateIfNotExist(val);
    int ret =  b->test->x;

    if(gRet == -1) {
        std::unique_lock<std::mutex> l(m);
        if(gRet == -1) {
            gRet = ret;
        }
    }

    if(ret != gRet) {
        std::cout << " FAILED " << std::endl;
    }
}

int main() {
    B b;

    std::vector<std::thread> threads;
    for(int i = 0; i < 10000; ++i) {
        threads.clear();
        for(int i = 0; i < 8; ++i) threads.emplace_back(&Func, &b, i);
        for(int i = 0; i < 8; ++i) threads[i].join();
    }
}

这是正确的方法吗? 有没有更好的方法来确保所有同时调用CreateIfNotExist()的线程都使用相同的shared_ptr?

遵循以下思路:

struct B {
  void CreateIfNotExist(int val) {
    std::call_once(test_init,
                   [this, val](){test = std::make_shared<A>(val);});
  }

  std::shared_ptr<A> test;
  std::once_flag test_init;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM