-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadMutexObject.h
132 lines (92 loc) · 2.43 KB
/
ThreadMutexObject.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*
* ThreadMutexObject.h
*
* Created on: 11 May 2012
* Author: thomas
*/
#ifndef THREADMUTEXOBJECT_H_
#define THREADMUTEXOBJECT_H_
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/condition_variable.hpp>
template <class T>
class ThreadMutexObject
{
public:
ThreadMutexObject()
{}
ThreadMutexObject(T initialValue)
: object(initialValue),
lastCopy(initialValue)
{}
void assignValue(T newValue)
{
boost::mutex::scoped_lock lock(mutex);
object = lastCopy = newValue;
lock.unlock();
}
boost::mutex & getMutex()
{
return mutex;
}
T & getReference()
{
return object;
}
void assignAndNotifyAll(T newValue)
{
boost::mutex::scoped_lock lock(mutex);
object = newValue;
signal.notify_all();
lock.unlock();
}
void notifyAll()
{
boost::mutex::scoped_lock lock(mutex);
signal.notify_all();
lock.unlock();
}
T getValue()
{
boost::mutex::scoped_lock lock(mutex);
lastCopy = object;
lock.unlock();
return lastCopy;
}
T waitForSignal()
{
boost::mutex::scoped_lock lock(mutex);
signal.wait(mutex);
lastCopy = object;
lock.unlock();
return lastCopy;
}
T getValueWait(int wait = 33000)
{
boost::this_thread::sleep(boost::posix_time::microseconds(wait));
boost::mutex::scoped_lock lock(mutex);
lastCopy = object;
lock.unlock();
return lastCopy;
}
T & getReferenceWait(int wait = 33000)
{
boost::this_thread::sleep(boost::posix_time::microseconds(wait));
boost::mutex::scoped_lock lock(mutex);
lastCopy = object;
lock.unlock();
return lastCopy;
}
void operator++(int)
{
boost::mutex::scoped_lock lock(mutex);
object++;
lock.unlock();
}
private:
T object;
T lastCopy;
boost::mutex mutex;
boost::condition_variable_any signal;
};
#endif /* THREADMUTEXOBJECT_H_ */