c++ - std::shared_ptr 在一位作家多读者设计中是线程安全的吗?

标签 c++ multithreading shared-ptr

在多线程服务器中,一个线程(编写器)定期从数据库更新数据,其他线程(读取器)使用此数据处理用户的请求。

我尝试使用读/写锁来满足这个请求,但是性能太差,所以需要寻找其他东西。

我读自 https://en.cppreference.com/w/cpp/memory/shared_ptr ,它说:

所有成员函数(包括复制构造函数和复制赋值)都可以由共享_ptr 的不同实例上的多个线程调用,而无需额外同步即使这些实例是同一对象的拷贝并共享同一对象的所有权

经过一番研究,我使用 std::shared_ptr 来做到这一点。代码如下所示。

// this class is singleton
class DataManager{
public:
    // all the reader thread use this method to get data and release shared_ptr 
    // at the end of user's request
    std::shared_ptr<Data> get_main_ptr(){
        return _main_data;
    }
private:
    // data1
    std::shared_ptr<Data> _main_data;
    // data2
    std::shared_ptr<Data> _back_data;

    // read database, write data in to _data
    void update_data(std::shared_ptr<Data> _data);

    // this function called at a separate thread every 10 min
    bool reload_data(){
        // write data in back pointer
        update_data(_back_data);

        //save the _main_data
        std::shared_ptr<Data> old_ptr = _main_data;

        //exchange pointer, reader thread hold the copy of _main_data
        _main_data = _back_data;

        // wait until reader threads release all copy of _main_data
        while(old_ptr.use_count() != 1) {
            sleep(5);
        }

        // clear the data
        old_ptr->clear();
        _back_data = old_ptr;
        return;
}

}

此方法在生产环境中似乎有效。但我不太确定也不了解shared_ptr的线程安全级别。这个方法有问题吗?或其他满足我要求的建议

最佳答案

看来您重新分配了 shared_ptr在线程之间共享:

_main_data = _back_data;

如果另一个线程读取或复制 _main_data同时它可能会得到一个损坏的拷贝。

分配给shared_ptr不是线程安全的,因为 shared_ptr包含两个指针成员,并且它们不能同时被原子更新。请参阅 shared_ptr :

If multiple threads of execution access the same shared_ptr without synchronization and any of those accesses uses a non-const member function of shared_ptr then a data race will occur;

要解决该竞争条件,代码需要使用 atomic_store :

atomic_store(&_main_data, _back_data);

读者必须这样做:

auto main_data = atomic_load(&_main_data);

Notes section有帮助:

These functions are typically implemented using mutexes, stored in a global hash table where the pointer value is used as the key.

To avoid data races, once a shared pointer is passed to any of these functions, it cannot be accessed non-atomically. In particular, you cannot dereference such a shared_ptr without first atomically loading it into another shared_ptr object, and then dereferencing through the second object.

The Concurrency TS offers atomic smart pointer classes atomic_shared_ptr and atomic_weak_ptr as a replacement for the use of these functions.

Since C++20: These functions were deprecated in favor of the specializations of the std::atomic template: std::atomic<std::shared_ptr> and std::atomic<std::weak_ptr>.


此外,您应该创建 Data析构函数执行所有清理工作,这样您就不必等到读取器线程释放 _main_data手动清理它。


或者,您可以使用std::atomicboost::intrusive_ptr使更新数据指针是线程安全的、原子的、无等待和无泄漏的。

使用boost::intrusive_ptr的好处而不是std::shared_ptr前者可以从普通指针线程安全地创建,因为原子引用计数存储在对象内部。

工作示例:

#include <iostream>
#include <atomic>

#include <boost/smart_ptr/intrusive_ptr.hpp>
#include <boost/smart_ptr/intrusive_ref_counter.hpp>

struct Data
    : boost::intrusive_ref_counter<Data, boost::thread_safe_counter>
{};

using DataPtr = boost::intrusive_ptr<Data>;

class DataAccessor
{
    std::atomic<Data*> data_ = 0;

public:
    ~DataAccessor() {
        DataPtr{data_.load(std::memory_order_acquire), false}; // Destroy data_.
    }

    DataPtr get_data() const {
        return DataPtr{data_.load(std::memory_order_acquire)};
    };

    void set_data(DataPtr new_data) {
        DataPtr old_data{data_.load(std::memory_order_relaxed), false}; // Destroy data_.
        data_.store(new_data.detach(), std::memory_order_release);
    }
};

int main() {
    DataAccessor da;

    DataPtr new_data{new Data};
    da.set_data(new_data);
    DataPtr old_data = da.get_data();
    std::cout << (new_data == old_data) << '\n';
}

valgrind运行:

$ valgrind ./test
==21502== Memcheck, a memory error detector
==21502== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==21502== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==21502== Command: ./test
==21502== 
1
==21502== 
==21502== HEAP SUMMARY:
==21502==     in use at exit: 0 bytes in 0 blocks
==21502==   total heap usage: 4 allocs, 4 frees, 73,736 bytes allocated
==21502== 
==21502== All heap blocks were freed -- no leaks are possible
==21502== 
==21502== For counts of detected and suppressed errors, rerun with: -v
==21502== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

关于c++ - std::shared_ptr 在一位作家多读者设计中是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55693819/

相关文章:

c++ - 指向shared_ptr的不透明类型C指针

c++ - 将 GoogleMock 与 Boost::Shared Pointers 一起使用时泄漏的模拟对象

c++ - 一个人如何降低 std::shared_ptr?

c++ - 为什么存在 shared_ptr 的原子重载

c++ - 使用 atoi 和错误 :unresolved external symbol

c++ - 如何从虚函数返回泛型派生类?

c++ - 如何在 Travis CI 中为 C++ with/CMake 项目正确配置 CodeCov?

java - RuleBasedCollat​​or 中的监控锁?

c# - 如何使用 TPL 在 C# 中编码(marshal)对特定线程的调用

python - python 中的奇怪线程行为