-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimedTask.h
More file actions
77 lines (66 loc) · 2.07 KB
/
Copy pathTimedTask.h
File metadata and controls
77 lines (66 loc) · 2.07 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
#pragma once
#include "TimedEvent.h"
#include <thread> // std::thread
#include <functional> // std::ref
#include <utility> // std::forward
namespace Utility
{
/**
* TimedTask.
* Manages acquisition of a resource subject to a timeout.
* The resource-specific functionalities are in the static
* methods of a template class argument.
* init_value : initialized resource result type.
* null_value : "failure" mode of the result type.
* acquire : obvious functionality.
* release : equally obvious functionality.
*
* NOTES:
* - result type must have value semantics (e.g., pointer).
* - acquire method must not block indefinitely.
* - object must persist until producer thread completes.
*/
template<typename Methods>
class TimedTask
{
public:
using Result = typename Methods::result_type;
TimedTask()
: result_(Methods::init_value())
{}
template<typename... Args>
TimedTask(Args&&... args)
: TimedTask()
{
std::thread(std::ref(*this), std::forward<Args>(args)...)
.detach();
}
// producer thread
template<typename... Args>
void operator()( Args&&... args )
{
Methods::acquire( result_, std::forward<Args>(args)... );
if ( window_.notify() ) { Methods::release( result_ ); }
}
// consumer thread; effective unit: milliseconds
Result wait( unsigned seconds, unsigned multiplier = 1000 )
{
return window_.wait( multiplier * seconds )
? result_
: Methods::null_value()
;
}
bool reset( bool force = false )
{
if ( window_.reset( force ) )
{
result_ = Methods::init_value();
return true;
}
return false;
}
private:
TimedEvent window_;
Result result_;
};
} // namespace Utility