-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjob.h
More file actions
92 lines (75 loc) · 2.27 KB
/
Copy pathjob.h
File metadata and controls
92 lines (75 loc) · 2.27 KB
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
#include <atomic>
#include <mutex>
#include <condition_variable>
#ifndef _JOB_H
#define _JOB_H
namespace job {
using Guard = std::unique_lock< std::mutex >;
template< typename T >
struct GuardedVar {
template< typename... Args >
GuardedVar( Args &&...args ) : value( std::forward< Args >( args )... ) {
ready = false;
canceled = false;
}
// try to assign value, if it is curretly being processed, no assignment
// is done and false is returned
bool tryAssign( T &val ) {
auto g = protect( std::try_to_lock );
if ( g.owns_lock() ) {
_assign( val );
return true;
}
return false;
}
// wait for value to be unguarded and assign it
void assign( T &val ) {
auto g = protect();
std::swap( this->value, val );
ready = true;
cond.notify_one();
}
// wait for value to be unguarded and assign it
void assign( T &&val ) {
auto g = protect();
this->value = std::move( val );
ready = true;
cond.notify_one();
}
// waits untill value is assigned and then runs callback which should accept
// one argument of type T &
// also invalidates value
template< typename Callback >
void waitAndReadOnce( Callback callback ) {
auto g = protect();
cond.wait( g, [&] { return ready || canceled; } ); // wait untill ready
if ( canceled )
return;
callback( value );
ready = false;
}
// try to copy value - if it is ready copy it out and invalidate it
// otherwise return default constructed value
// first element of tuple signifies if value was present
std::pair< bool, T > tryCopyOut() {
if ( ready ) {
auto g = protect();
if ( ready ) {
ready = false;
return { true, value };
}
}
return { false, T() };
}
void cancelWaits() { canceled = true; cond.notify_all(); }
private:
std::mutex mutex;
std::condition_variable cond;
T value;
std::atomic< bool > ready;
std::atomic< bool > canceled;
template< typename... Args >
Guard protect( Args... args ) { return Guard( mutex, args... ); }
};
} // namespace job
#endif // _JOB_H