C++ Logo

std-proposals

Advanced search

[std-proposals] Idea for a "null" mutex

From: Simon Scatton <simon.scatton_at_[hidden]>
Date: Mon, 2 Jan 2023 03:22:31 +0000
Hello everyone, I am currently implementing a generic logger that should be thread-safe. To make sure I rewrite as little code as possible, I am templating a class as follows: template <typename Mutex> class Output { public: void write(); protected: Mutex mutex_; }; And I have a "null mutex" that is a struct like this: struct NullMutex { void lock() {} void unlock() noexcept {} bool try_lock() { return true; } }; So that for instance if I want a thread safe Output, I use this: Output<std::mutex> A; And if I want a non-thread safe Output I use this: Output<NullMutex> B; The core of the write() function being something like this: template <typename Mutex> void Output<Mutex>::write() { const std::lock_guard<Mutex> lock(mutex_); // ... } I have not found any C++ official resources about this. Has this been already addressed in C++ standard discussion around mutexes ? Do you think adding such a "null mutex" would be useful? I would love to hear what you think about this. Kind regards, -- Simon Scatton

Received on 2023-01-02 03:22:33