mrs_lib
Various reusable classes, functions and utilities for use in MRS projects
mutex.h
Go to the documentation of this file.
1 
5 #ifndef MUTEX_H
6 #define MUTEX_H
7 
8 #include <iostream>
9 #include <mutex>
10 #include <tuple>
11 
12 namespace mrs_lib
13 {
14 
27 template <class... GetArgs, class... SetArgs>
28 std::tuple<GetArgs...> get_set_mutexed(std::mutex& mut, std::tuple<GetArgs&...> get, std::tuple<SetArgs...> from_set, std::tuple<SetArgs&...> to_set) {
29 
30  std::scoped_lock lock(mut);
31 
32  std::tuple<GetArgs...> result = get;
33  to_set = from_set;
34 
35  return result;
36 }
37 
47 template <class... Args>
48 std::tuple<Args...> get_mutexed(std::mutex& mut, Args&... args) {
49 
50  std::scoped_lock lock(mut);
51 
52  std::tuple result = std::tuple(args...);
53 
54  return result;
55 }
56 
57 
67 template <class T>
68 T get_mutexed(std::mutex& mut, T& arg) {
69 
70  std::scoped_lock lock(mut);
71 
72  return arg;
73 }
74 
82 template <class T>
83 void set_mutexed_impl(const T what, T& where) {
84 
85  where = what;
86 }
87 
97 template <class T, class... Args>
98 void set_mutexed_impl(const T what, T& where, Args... args) {
99 
100  where = what;
101 
102  set_mutexed_impl(args...);
103 }
104 
115 template <class T>
116 auto set_mutexed(std::mutex& mut, const T what, T& where) {
117 
118  std::scoped_lock lock(mut);
119 
120  where = what;
121 
122  return where;
123 }
124 
139 template <class... Args>
140 auto set_mutexed(std::mutex& mut, Args&... args) {
141 
142  std::scoped_lock lock(mut);
143 
144  set_mutexed_impl(args...);
145 
146  return std::tuple(args...);
147 }
148 
164 template <class... Args>
165 auto set_mutexed(std::mutex& mut, const std::tuple<Args...> from, std::tuple<Args&...> to) {
166 
167  std::scoped_lock lock(mut);
168 
169  to = from;
170 
171  return to;
172 }
173 
174 } // namespace mrs_lib
175 
176 #endif
mrs_lib::get_mutexed
std::tuple< Args... > get_mutexed(std::mutex &mut, Args &... args)
thread-safe getter for values of variables (args)
Definition: mutex.h:48
mrs_lib::set_mutexed_impl
void set_mutexed_impl(const T what, T &where)
base case of the variadic template for set_mutexed()
Definition: mutex.h:83
mrs_lib
All mrs_lib functions, classes, variables and definitions are contained in this namespace.
Definition: attitude_converter.h:29
mrs_lib::get_set_mutexed
std::tuple< GetArgs... > get_set_mutexed(std::mutex &mut, std::tuple< GetArgs &... > get, std::tuple< SetArgs... > from_set, std::tuple< SetArgs &... > to_set)
thread-safe getter and setter for values of variables (args)
Definition: mutex.h:28
mrs_lib::set_mutexed
auto set_mutexed(std::mutex &mut, const T what, T &where)
thread-safe setter for a variable
Definition: mutex.h:116