-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.cpp
73 lines (56 loc) · 1.62 KB
/
main.cpp
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
#include <thread_local.hpp>
#include <runloop.hpp>
#include <thread>
#include <iostream>
#include <string>
#include <mutex>
#include <memory>
class Task {
public:
Task(Runloop &loop)
: _loop(loop),
alive(true),
thread(
[this]() {
std::cout << "Task: Doing some work" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
onDone();
}) {
}
~Task() {
std::cout << "Task::~Task" << std::endl;
std::lock_guard<std::mutex> lock(mutex);
alive = false;
thread.detach();
}
void onDone() {
std::cout << "Task::~onDone" << std::endl;
std::lock_guard<std::mutex> lock(mutex);
if (alive) {
_loop.invoke([] {
std::cout << "Done" << std::endl;
});
}
}
private:
Runloop &_loop;
bool alive;
std::mutex mutex;
std::thread thread;
};
int main() {
std::cout << "Starting loop on: " << std::this_thread::get_id() << std::endl;
Runloop runloop;
std::vector<std::unique_ptr<Task>> tasks;
tasks.push_back(std::make_unique<Task>(runloop));
runloop.invoke([&] {
std::cout << "Doing some heavy processing" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "Canceling outstanding tasks" << std::endl;
tasks.clear();
std::cout << "Stopping runLoop" << std::endl;
runloop.stop();
});
runloop.run();
std::cout << "End of loop" << std::endl;
}