examples

Toy examples in single C files.
git clone git://henryandlizzy.uk/examples
Log | Files | Refs

commit 9024f9695a499277fd274b713a26bad1994ee2d9
parent f357d93a8859b6ff598392d2fe138550df92e5c6
Author: Henry Wilson <henry@henryandlizzy.uk>
Date:   Thu, 28 Apr 2022 15:53:48 +0000

Add mutex-wrapping container C++ example.

Diffstat:
Asrc/mutex_container.cpp | 47+++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 47 insertions(+), 0 deletions(-)

diff --git a/src/mutex_container.cpp b/src/mutex_container.cpp @@ -0,0 +1,47 @@ +#include <thread> +#include <mutex> + +template <typename T, typename M = std::mutex> +struct mutex_container +{ + mutex_container() = default; + + struct access + { + T* operator ->() + { + return &ref; + } + private: + friend mutex_container; + access(M& m, T& r) + : lock(m) + , ref(r) + {} + std::lock_guard<M> lock; + T& ref; + }; + + access lock() + { + return {mut, val}; + } + +private: + M mut; + T val; +}; + +struct mystruct +{ + int x; +}; + +int main() +{ + mutex_container<mystruct> x; + auto lock = x.lock(); + + lock->x = 5; + lock->x++; +}