examples

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

mutex_container.cpp (528B)


      1 #include <thread>
      2 #include <mutex>
      3 
      4 template <typename T, typename M = std::mutex>
      5 struct mutex_container
      6 {
      7 	mutex_container() = default;
      8 
      9 	struct access
     10 	{
     11 		T* operator ->()
     12 		{
     13 			return &ref;
     14 		}
     15 	private:
     16 		friend mutex_container;
     17 		access(M& m, T& r)
     18 		:   lock(m)
     19 		,   ref(r)
     20 		{}
     21 		std::lock_guard<M> lock;
     22 		T& ref;
     23 	};
     24 
     25 	access lock()
     26 	{
     27 		return {mut, val};
     28 	}
     29 
     30 private:
     31 	M mut;
     32 	T val;
     33 };
     34 
     35 struct mystruct
     36 {
     37 	int x;
     38 };
     39 
     40 int main()
     41 {
     42 	mutex_container<mystruct> x;
     43 	auto lock = x.lock();
     44 
     45 	lock->x = 5;
     46 	lock->x++;
     47 }