1 |
/* |
2 |
Copyright (C) 2013 Christian Schoenebeck |
3 |
*/ |
4 |
|
5 |
#ifndef LS_CHANGEFLAGRELAXED_H |
6 |
#define LS_CHANGEFLAGRELAXED_H |
7 |
|
8 |
#include "atomic.h" |
9 |
|
10 |
/** |
11 |
* May be used as boolean variable to synchronize that some shared resource has |
12 |
* been changed, with relaxed memory order. It is designed for exactly 1 reading |
13 |
* thread (calling readAndReset()) and n writing threads (calling raise()). |
14 |
* Synchronization with "relaxed memory order" means here that the information |
15 |
* written by raise() calls are never lost, but it may take some time to |
16 |
* propagate to the reading thread, thus readAndReset() may not always return |
17 |
* the very latest information. So the informations might be delivered with a |
18 |
* delay. |
19 |
*/ |
20 |
class ChangeFlagRelaxed { |
21 |
public: |
22 |
ChangeFlagRelaxed() { |
23 |
newval = (atomic_t) ATOMIC_INIT(0); |
24 |
oldval = 0; |
25 |
} |
26 |
|
27 |
inline bool readAndReset() { |
28 |
int v = atomic_read(&newval); |
29 |
bool changed = (oldval != v); |
30 |
oldval = v; |
31 |
return changed; |
32 |
} |
33 |
|
34 |
inline void raise() { |
35 |
atomic_inc(&newval); |
36 |
} |
37 |
private: |
38 |
atomic_t newval; |
39 |
int oldval; |
40 |
}; |
41 |
|
42 |
#endif // LS_CHANGEFLAGRELAXED_H |