-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathexample.cpp
More file actions
87 lines (64 loc) · 2 KB
/
example.cpp
File metadata and controls
87 lines (64 loc) · 2 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
#include <iostream>
#include <sstream>
#include <random>
#include "ThreadPool.hpp"
void hello()
{
std::cout << "hello from thread #" << std::this_thread::get_id() << "!\n";
}
void hola()
{
std::cout << "hola from thread #" << std::this_thread::get_id() << "!\n";
}
int add(int x, int y)
{
return x + y;
}
int main(int argc, char** argv)
{
using namespace dbr;
cc::ThreadPool pool;
// queue up 200 jobs, then run them
pool.pause(true);
for (int i = 0; i < 200; ++i)
pool.add(i % 2 == 1 ? hello : hola);
pool.pause(false);
// wait for all jobs to finish
pool.wait();
std::cout << std::endl;
std::random_device rd;
std::default_random_engine rand(rd());
std::uniform_int_distribution<int> dist(1, 100);
// get ids of threads being used
for (auto& id : pool.ids())
std::cout << "Thread ID: " << id << std::endl;
std::cout << std::endl;
std::vector<std::tuple<int, int, std::future<int>>> results;
// add 100 more jobs of a different function type, using the same pool
// these will start executing immediately
for (int i = 0; i < 100; ++i)
{
auto one = dist(rand);
auto two = dist(rand);
results.emplace_back(one, two, pool.add(add, one, two));
}
// wait until those are all done
pool.wait();
for (auto& res : results)
std::cout << std::get<0>(res) << " + " << std::get<1>(res) << " = " << std::get<2>(res).get() << std::endl;
std::cout << std::endl;
results.clear();
// now add some more, using a lambda
for (int i = 0; i < 100; ++i)
{
auto one = dist(rand);
auto two = dist(rand);
results.emplace_back(one, two, pool.add([](auto x, auto y) { return x - y; }, one, two));
}
// wait until those are all done
pool.wait();
for (auto& res : results)
std::cout << std::get<0>(res) << " - " << std::get<1>(res) << " = " << std::get<2>(res).get() << std::endl;
std::cout << std::endl;
return 0;
}