Last active
August 20, 2024 11:37
-
-
Save flomnes/54c89bc3ef48090bd3bf2e46692cc79d to your computer and use it in GitHub Desktop.
Injected mutex & null pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cassert> | |
#include <mutex> | |
#include <vector> | |
class IMutex | |
{ | |
public: | |
virtual void lock() = 0; | |
virtual void unlock() noexcept = 0; | |
}; | |
class StdMutex: public IMutex | |
{ | |
public: | |
void lock() override | |
{ | |
mut_.lock(); | |
} | |
void unlock() noexcept override | |
{ | |
mut_.unlock(); | |
} | |
private: | |
std::mutex mut_; | |
}; | |
class NullMutex: public IMutex | |
{ | |
public: | |
void lock() override | |
{ | |
} | |
void unlock() noexcept override | |
{ | |
} | |
}; | |
template<class T> | |
class ResourceOwner | |
{ | |
public: | |
ResourceOwner(IMutex& mut): | |
mut_(mut) | |
{ | |
} | |
void push_back(const T& elt) | |
{ | |
std::lock_guard<IMutex> lock(mut_); | |
vec_.push_back(elt); | |
} | |
T operator[](std::size_t idx) const | |
{ | |
std::lock_guard<IMutex> lock(mut_); | |
return vec_[idx]; | |
} | |
private: | |
std::vector<T> vec_; | |
IMutex& mut_; | |
}; | |
double example(IMutex& mut) | |
{ | |
ResourceOwner<double> p(mut); | |
p.push_back(332); | |
p.push_back(221); | |
return p[0] + p[1]; | |
} | |
int main() | |
{ | |
constexpr double reference = 332 + 221; | |
{ | |
NullMutex null; | |
assert(example(null) == reference); | |
} | |
{ | |
StdMutex mutex; | |
assert(example(mutex) == reference); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment