trikRuntime
synchronizedVar.h
Go to the documentation of this file.
1 /* Copyright 2015 CyberTech Labs Ltd.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License. */
14 
15 #pragma once
16 
17 #include <QtCore/QScopedPointer>
18 #include <QtCore/QReadWriteLock>
19 
20 #include "commandLineParser.h"
21 
22 namespace trikKernel {
23 
34 template<typename T> class SynchronizedVar
35 {
36 public:
39  : mValue(new T())
40  , mBuffer(new T())
41  {
42  }
43 
45  inline T get()
46  {
47  mLock.lockForRead();
48  T temp = *mValue;
49  mLock.unlock();
50  return temp;
51  }
52 
55  inline T *operator->()
56  {
57  return mBuffer.data();
58  }
59 
62  inline const T &operator*() const
63  {
64  return *mBuffer;
65  }
66 
69  inline void sync()
70  {
71  mLock.lockForWrite();
72  mValue.swap(mBuffer);
73  mLock.unlock();
74  }
75 
78  inline void reset()
79  {
80  mLock.lockForWrite();
81  mValue.reset(new T());
82  mBuffer.reset(new T());
83  mLock.unlock();
84  }
85 
86 private:
88  QScopedPointer<T> mValue;
89 
91  QScopedPointer<T> mBuffer;
92 
94  QReadWriteLock mLock;
95 };
96 
97 }
Definition: analogSensor.h:23
void sync()
Copies value from buffer to synced value, invalidates buffer.
Definition: synchronizedVar.h:69
void reset()
Resets buffer to initial state.
Definition: synchronizedVar.h:78
T * operator->()
Returns pointer to unsynced buffer.
Definition: synchronizedVar.h:55
Helper template for syncing reader and writer.
Definition: synchronizedVar.h:34
const T & operator*() const
Returns contents of unsynced buffer.
Definition: synchronizedVar.h:62
SynchronizedVar()
Constructor. Creates var with default buffer and value.
Definition: synchronizedVar.h:38