-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFuture.h
More file actions
76 lines (60 loc) · 1.99 KB
/
Copy pathFuture.h
File metadata and controls
76 lines (60 loc) · 1.99 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
#pragma once
template <typename T>
class Future {
private:
struct SharedState {
T result;
bool ready = false;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
};
SharedState* state;
static void execute(void* arg) {
auto* stateFuncPair = static_cast<std::pair<SharedState*, T(*)()>*>(arg);
SharedState* state = stateFuncPair->first;
T (*func)() = stateFuncPair->second;
delete stateFuncPair; // delete because it was allocated in the constructor
T result = func();
pthread_mutex_lock(&state->mutex);
state->result = result;
state->ready = true;
pthread_cond_signal(&state->cond);
pthread_mutex_unlock(&state->mutex);
}
public:
Future(ThreadPool& pool, T (*func)()) {
state = new SharedState;
auto* arg = new std::pair<SharedState*, T(*)()>(state, func);
// put the function in the thread pool
pool.submit(execute, arg);
}
// Future(T (*func)()) {
// state = new SharedState;
// auto* arg = new std::pair<SharedState*, T(*)()>(state, func);
// // put the function in a thread
// pthread_t thread;
// pthread_create(&thread, nullptr, execute, arg);
// pthread_detach(thread); // detach the thread to avoid memory leaks
// }
bool ready() {
pthread_mutex_lock(&state->mutex);
bool isReady = state->ready;
pthread_mutex_unlock(&state->mutex);
return isReady;
}
// block until the result is ready
T get() {
pthread_mutex_lock(&state->mutex);
while (!state->ready) {
pthread_cond_wait(&state->cond, &state->mutex);
}
T result = state->result;
pthread_mutex_unlock(&state->mutex);
return result;
}
~Future() {
pthread_mutex_destroy(&state->mutex);
pthread_cond_destroy(&state->cond);
delete state;
}
};