This repository contains the class mutex_protected
, which is a mutex
that owns
the value it protects, and uses the type system and RAII to enforce that only one
thread can access it at any given time.
It is clearly possible to do the same thing with std::mutex
and std::lock_guard
,
but those are easy to misuse, accessing a variable without locking the mutex.
The goal of this project is to push an implementation of mutex_protected
to the
C++ Standard Library. Similar implementations exist in
Boost and
Folly.
The mutex_protected
class template is header-only. To use it, include the
header mutex_protected.h
in your project.
#include <thread>
#include <vector>
#include "mutex_protected.h"
int main() {
mutex_protected<int> value(0);
std::vector<std::thread> threads;
threads.reserve(10);
for (int i = 0; i < 10; ++i) {
threads.emplace_back([&value]() {
for (int j = 0; j < 10000; ++j) {
*value.lock() += 1;
}
});
}
for (auto& thread : threads) {
thread.join();
}
return *value.lock() == 100000;
}
This code is licensed under the MIT License. See LICENSE for details.
For building and working with the project, please see the developer guide.
Press .
or visit [https://github.dev/jbcoe/mutex_protected] to open the project in
an instant, cloud-based, development environment. We have defined a
devcontainer that will automatically install
the dependencies required to build and test the project.