|
Mutexed 0.0.1
A header-only mutex-protected value wrapper for C++20.
|
A header-only mutex-protected value wrapper for C++20.
Using mutexes on their own to protect data from concurrent access impose doing specific actions that may be forgotten by the user, making it error-prone :
The Mutexed class prevents the user from accessing the data without its dedicated mutex being locked.
Two ways of accessing the protected data are provided :
using locked() :
Note that the type of words is std::string&.
using with_locked() :
The Mutexed class detects if the mutex is shared_lockable (a concept that checks if it has the lock_shared()-associated functions) and uses lock_shared() on each of the following circumstances :
const&Mutexed is const when any of with_locked(), locked() or when_all_locked() is calledAcquiring more that one mutex is error-prone, that is why the standard library provides the free function std::lock().
The llh::mutexed::with_all_locked pseudo-free-function calls std::lock() under the hood and is used like this :
You may optionally have your Mutexed object hold a condition-variable by providing has_cv as its last template argument.
The non-const versions of with_locked() and locked() will call notify_all() on the condition-variable after the mutex have been unlocked.
The Mutexed class has the three member-functions
wait(Predicate&&)wait_for(std::chrono::duration const&, Predicate&&)wait_until(std::chrono::time_point const&, Predicate&&)that mirror the standard library's member functions of std::condition_variable_any called with a lock that is shared if the mutex is shared_lockable .
The tests confirm that the number of times the inner mutex is acquired is exactly once for both of the ways to access the protected data.
This library currently requires C++20.
It has been tested in the following environments :
auto const for the structured bindingswith_all_locked take the function as its last argument instead of firstMutexeds#ifdefs