C++ Logo

std-proposals

Advanced search

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

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Mon, 02 Jan 2023 10:06:52 +0000
Hi,

On 2 January 2023 03:22:31 GMT, Simon Scatton via Std-Proposals <std-proposals_at_[hidden]> wrote:
>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,
>

Yes, it definitely makes sense. I saw a similar type used in Boost.ASIO:

https://github.com/boostorg/asio/blob/develop/include/boost/asio/detail/null_mutex.hpp#L29

For example it is used for implementing basic_channel (null mutex) and basic_concurrent_channel (some regular mutex), employing the same pattern you described.

I think it might be worth adding to the standard library.

Cheers,
Lénárd

Received on 2023-01-02 10:06:57