spielwiese
Last change
on this file since 54b24c was
54b24c,
checked in by Reimer Behrends <behrends@…>, 5 years ago
|
Finalizing thread support.
|
-
Property mode set to
100644
|
File size:
924 bytes
|
Line | |
---|
1 | #ifndef _SINGULAR_LIBTHREAD_SYNCVAR |
---|
2 | #define _SINGULAR_LIBTHREAD_SYNCVAR |
---|
3 | |
---|
4 | #include "singthreads.h" |
---|
5 | #include "thread.h" |
---|
6 | #include <queue> |
---|
7 | |
---|
8 | namespace LibThread { |
---|
9 | |
---|
10 | template <typename T> |
---|
11 | class SyncVar { |
---|
12 | private: |
---|
13 | Lock lock; |
---|
14 | ConditionVariable cond; |
---|
15 | int waiting; |
---|
16 | bool init; |
---|
17 | T value; |
---|
18 | public: |
---|
19 | SyncVar() : lock(), cond(&lock), waiting(0), init(false) { |
---|
20 | } |
---|
21 | void write(T& value) { |
---|
22 | lock.lock(); |
---|
23 | if (!init) { |
---|
24 | this->value = value; |
---|
25 | this->init = true; |
---|
26 | } |
---|
27 | if (waiting) |
---|
28 | cond.signal(); |
---|
29 | lock.unlock(); |
---|
30 | } |
---|
31 | void read(T& result) { |
---|
32 | lock.lock(); |
---|
33 | waiting++; |
---|
34 | while (!init) |
---|
35 | cond.wait(); |
---|
36 | waiting--; |
---|
37 | if (waiting) |
---|
38 | cond.signal(); |
---|
39 | lock.unlock(); |
---|
40 | } |
---|
41 | bool try_read(T& result) { |
---|
42 | bool success; |
---|
43 | lock.lock(); |
---|
44 | success = init; |
---|
45 | if (success) { |
---|
46 | result = value; |
---|
47 | } |
---|
48 | lock.unlock(); |
---|
49 | return success; |
---|
50 | } |
---|
51 | }; |
---|
52 | |
---|
53 | } |
---|
54 | |
---|
55 | #endif // _SINGULAR_LIBTHREAD_SYNCVAR |
---|
Note: See
TracBrowser
for help on using the repository browser.