Main MRPT website > C++ reference
MRPT logo
CThreadSafeVariable.h
Go to the documentation of this file.
1 /* +---------------------------------------------------------------------------+
2  | The Mobile Robot Programming Toolkit (MRPT) C++ library |
3  | |
4  | http://www.mrpt.org/ |
5  | |
6  | Copyright (C) 2005-2012 University of Malaga |
7  | |
8  | This software was written by the Machine Perception and Intelligent |
9  | Robotics Lab, University of Malaga (Spain). |
10  | Contact: Jose-Luis Blanco <jlblanco@ctima.uma.es> |
11  | |
12  | This file is part of the MRPT project. |
13  | |
14  | MRPT is free software: you can redistribute it and/or modify |
15  | it under the terms of the GNU General Public License as published by |
16  | the Free Software Foundation, either version 3 of the License, or |
17  | (at your option) any later version. |
18  | |
19  | MRPT is distributed in the hope that it will be useful, |
20  | but WITHOUT ANY WARRANTY; without even the implied warranty of |
21  | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
22  | GNU General Public License for more details. |
23  | |
24  | You should have received a copy of the GNU General Public License |
25  | along with MRPT. If not, see <http://www.gnu.org/licenses/>. |
26  | |
27  +---------------------------------------------------------------------------+ */
28 #ifndef mrpt_synch_threadsafevar_H
29 #define mrpt_synch_threadsafevar_H
30 
32 
33 namespace mrpt
34 {
35 namespace synch
36 {
37 
38  /** A template for created thread-safe variables with an internal critical section controlled each read or write.
39  * Example:
40  * \code
41  * CThreadSafeVariable<double> var1;
42  * ...
43  * var.set(2.3); // Sets the value
44  * double x = var.get(); // Reads the variable
45  * ...
46  * double foo = var; // Also reads the variable
47  * var = 2.3; // ERROR: Not allowed, use ".set()" instead.
48  * \endcode
49  *
50  * \sa CCriticalSection
51  * \ingroup synch_grp
52  */
53  template <typename T>
55  {
56  private:
58  T m_val;
59  public:
61  CThreadSafeVariable(const T& init_val) : m_cs(), m_val(init_val) { }
62 
63  virtual ~CThreadSafeVariable() { }
64 
65  /** Return a copy of the hold variable */
66  T get() const
67  {
68  T ret;
69  {
71  ret = m_val;
72  }
73  return ret;
74  }
75 
76  /** Return a copy of the hold variable */
77  void get(T &out_val) const
78  {
80  out_val = m_val;
81  }
82 
83  /** Return a copy of the hold variable */
84  operator T(void) const
85  {
87  return m_val;
88  }
89 
90  /** Return a copy of the hold variable */
91  void set(const T &new_val)
92  {
94  m_val = new_val;
95  }
96 
97  /** Swap the current value of the hold variable and the passed one, as one atomic operation. */
98  void swap(T &in_out_var)
99  {
101  std::swap(in_out_var,m_val);
102  }
103  };
104 
105 } // End of namespace
106 } // End of namespace
107 
108 #endif



Page generated by Doxygen 1.8.3 for MRPT 0.9.6 SVN: at Fri Feb 15 22:05:02 EST 2013