Main MRPT website > C++ reference for MRPT 1.5.7
CThreadSafeVariable.h
Go to the documentation of this file.
1 /* +---------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | http://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
6  | See: http://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See details in http://www.mrpt.org/License |
8  +---------------------------------------------------------------------------+ */
9 #ifndef mrpt_synch_threadsafevar_H
10 #define mrpt_synch_threadsafevar_H
11 
13 
14 namespace mrpt
15 {
16 namespace synch
17 {
18 
19  /** A template for created thread-safe variables with an internal critical section controlled each read or write.
20  * Example:
21  * \code
22  * CThreadSafeVariable<double> var1;
23  * ...
24  * var.set(2.3); // Sets the value
25  * double x = var.get(); // Reads the variable
26  * ...
27  * double foo = var; // Also reads the variable
28  * var = 2.3; // ERROR: Not allowed, use ".set()" instead.
29  * \endcode
30  *
31  * \sa CCriticalSection
32  * \ingroup synch_grp
33  */
34  template <typename T>
36  {
37  private:
39  T m_val;
40  public:
42  CThreadSafeVariable(const T& init_val) : m_cs(), m_val(init_val) { }
43 
44  virtual ~CThreadSafeVariable() { }
45 
46  /** Return a copy of the hold variable */
47  T get() const
48  {
49  T ret;
50  {
52  ret = m_val;
53  }
54  return ret;
55  }
56 
57  /** Return a copy of the hold variable */
58  void get(T &out_val) const
59  {
61  out_val = m_val;
62  }
63 
64  /** Return a copy of the hold variable */
65  operator T(void) const
66  {
68  return m_val;
69  }
70 
71  /** Return a copy of the hold variable */
72  void set(const T &new_val)
73  {
75  m_val = new_val;
76  }
77 
78  /** Swap the current value of the hold variable and the passed one, as one atomic operation. */
79  void swap(T &in_out_var)
80  {
82  std::swap(in_out_var,m_val);
83  }
84  };
85 
86 } // End of namespace
87 } // End of namespace
88 
89 #endif
A template for created thread-safe variables with an internal critical section controlled each read o...
This class provides simple critical sections functionality.
A class acquiring a CCriticalSection at its constructor, and releasing it at destructor.
void swap(T &in_out_var)
Swap the current value of the hold variable and the passed one, as one atomic operation.
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.



Page generated by Doxygen 1.8.14 for MRPT 1.5.7 Git: 5902e14cc Wed Apr 24 15:04:01 2019 +0200 at lun oct 28 01:39:17 CET 2019