-
Notifications
You must be signed in to change notification settings - Fork 107
/
main.cpp
125 lines (97 loc) · 2.7 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// Amost all the code for this example is in this header
#include <boost/thread/thread.hpp>
namespace detail {
template <class T>
struct task_wrapped {
private:
T task_unwrapped_;
public:
explicit task_wrapped(const T& f)
: task_unwrapped_(f)
{}
void operator()() const {
// Resetting interruption.
try {
boost::this_thread::interruption_point();
} catch(const boost::thread_interrupted&){}
try {
// Executing task.
task_unwrapped_();
} catch (const std::exception& e) {
std::cerr<< "Exception: " << e.what() << '\n';
} catch (const boost::thread_interrupted&) {
std::cerr<< "Thread interrupted\n";
} catch (...) {
std::cerr<< "Unknown exception\n";
}
}
};
} // namespace detail
namespace detail {
template <class T>
task_wrapped<T> make_task_wrapped(const T& task_unwrapped) {
return task_wrapped<T>(task_unwrapped);
}
} // namespace detail
#include <boost/asio/io_service.hpp>
namespace tp_base {
class tasks_processor: private boost::noncopyable {
protected:
static boost::asio::io_service& get_ios() {
static boost::asio::io_service ios;
static boost::asio::io_service::work work(ios);
return ios;
}
public:
template <class T>
static void push_task(const T& task_unwrapped) {
get_ios().post(detail::make_task_wrapped(task_unwrapped));
}
static void start() {
get_ios().run();
}
static void stop() {
get_ios().stop();
}
}; // tasks_processor
} // namespace tp_base
using namespace tp_base;
int func_test() {
static int counter = 0;
++ counter;
boost::this_thread::interruption_point();
switch (counter) {
case 3:
throw std::logic_error("Just checking");
case 10:
// Emulation of thread interruption.
// Caught inside task_wrapped and does not stop execution.
throw boost::thread_interrupted();
case 90:
// Stopping the tasks_processor.
tasks_processor::stop();
}
return counter;
}
int main () {
for (std::size_t i = 0; i < 100; ++i) {
tasks_processor::push_task(&func_test);
}
// Processing was not started.
assert(func_test() == 1);
// We can also use lambda as a task.
#ifndef BOOST_NO_CXX11_LAMBDAS
// Counting 2 + 2 asynchronously.
int sum = 0;
tasks_processor::push_task(
[&sum]() { sum = 2 + 2; }
);
// Processing was not started.
assert(sum == 0);
#endif
// Does not throw, but blocks till
// one of the tasks it is owning
// calls tasks_processor::stop().
tasks_processor::start();
assert(func_test() == 91);
}