-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSyncValue.h
56 lines (51 loc) · 1.27 KB
/
SyncValue.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
#pragma once
//Author: Ugo Varetto
//! \file SyncValue.h
//! \brief Synchronized value access
//!
#include <deque>
#include <mutex>
#include <condition_variable>
//! Synchronized value:
//! @c Get() waits for data
template<typename T>
class SyncValue {
public:
//! Put
void Put(T&& v) {
std::lock_guard<std::mutex> guard(mutex_);
value_ = std::move(v); //MUST HAVE AN OVERLOADED operator=(T&&)
empty_ = false;
cond_.notify_one(); //notify
}
//! Return and remove element in front of queue.
//! Waits indefinitely for an element to be available.
T Get() {
std::unique_lock<std::mutex> lock(mutex_);
//stop and wait for notification if condition is false;
//continue otherwise
cond_.wait(lock, [this] { return !empty_; });
T e(std::move(value_));
empty_ = true;
return e;
}
void Finish() {
done_ = true;
Put(T());
}
//! Empty ?
bool Empty() const {
return empty_;
}
bool Done() const {
return done_;
}
void Reset() { done_ = false; }
bool operator!() const { return Done(); }
private:
T value_;
bool empty_ = true;
mutable std::mutex mutex_;
std::condition_variable cond_;
bool done_ = false;
};