Debian Codegraph @

CriticalData.hpp

raw
1 /*
2 * CriticalData.hpp
3 *
4 * Copyright 2020 Kevin Krüger <[email protected]>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 * MA 02110-1301, USA.
20 *
21 *
22 */
23
24 #ifndef _CRITICALDATA_H_INCLUDED_
25 #define _CRITICALDATA_H_INCLUDED_
26
27 #include <cstdint>
28 #include <mutex>
29 #include "config.h"
30
31 namespace SerialDeviceControl
32 {
33 //simple mutex container, protecting its content from concurrently access and its side effects.
34 //intended for simple data types.
35 template<typename T>
36 class CriticalData
37 {
38 public:
39 //default constructure, leaves the contained object uninitialized.
40 CriticalData()
41 {
42
43 }
44
45 //constructor setting the contained object to the initial value.
46 CriticalData(T initialValue) :
47 mData(initialValue)
48 {
49
50 }
51
52 virtual ~CriticalData()
53 {
54
55 }
56
57 //return the value of the contained data object.
58 T Get()
59 {
60 T val;
61
62 {
63 std::lock_guard<std::mutex> guard(mMutex);
64 val = mData;
65 }
66
67 return val;
68
69 }
70
71 //set the value of the contained data object.
72 void Set(T value)
73 {
74 {
75 std::lock_guard<std::mutex> guard(mMutex);
76 mData = value;
77 }
78 }
79
80 private:
81 //instance of the data type.
82 T mData;
83 //mutex protecting the data object.
84 std::mutex mMutex;
85 };
86 }
87
88 #endif