0

I'm developing a multi-threaded C++ project and have a variable that should be accessed atomically for reading and writing. I use this simple self-written wrapper to avoid race conditions:

template<typename T>
class Locker final {
    std::mutex mutex;
    T value{};
public:
    explicit Locker(const T& value_) : value(value_) {};
    inline T get() { std::lock_guard<std::mutex> guard(mutex); return value; }
    inline void set(const T& value_) { std::lock_guard<std::mutex> guard(mutex); value = value_; }
};

I've read that the std::atomic class does similar things, but it only works for TriviallyCopyable types and I want to store different non-TriviallyCopyable types. Does modern C++ provide built-in alternatives for this purpose?

I want for some data to be updated asynchronously on timeout, and non-updatable threads have safe access to it.

Alvov1
  • 157
  • 1
  • 2
  • 10
  • 2
    No. You have to do synchronization manually, unless stated in the docs. – Michael Chourdakis Jul 26 '22 at 12:29
  • 1
    Boost has some thread safe containers. Check out their [lockfree library](https://theboostcpplibraries.com/boost.lockfree). – NathanOliver Jul 26 '22 at 12:31
  • If the STL containers like `std::vector` and `std::string` were made *inherently* thread-safe, then they would also be inherently less efficient, I guess. That's probably not what the majority of users would want. – Adrian Mole Jul 26 '22 at 12:32
  • 2
    This kind of synchronization is dangerous, because when applied without care, you could end up with lots of lock/unlock operations which perform badly and have the risk of deadlocks. Make threads cooperate, not compete for resources. – Ulrich Eckhardt Jul 26 '22 at 12:33
  • @AdrianMole I don't want those types (std::vector, std::string..) to be thread safe. You must have misunderstood my question. – Alvov1 Jul 26 '22 at 12:39
  • @UlrichEckhardt Resource access will happen very infrequently, but when it does, it must be thread-safe. I want some data to be updated asynchronously on timeout, and non-updatable threads have safe access to it. – Alvov1 Jul 26 '22 at 12:43
  • For `T` in the above, why not `std::atomic` ? – Richard Critten Jul 26 '22 at 12:57
  • @RichardCritten See the [documentation](https://en.cppreference.com/w/cpp/atomic/atomic): The primary std::atomic template may be instantiated with any TriviallyCopyable type T satisfying both CopyConstructible and CopyAssignable. – Alvov1 Jul 26 '22 at 13:07

0 Answers0