forked from changkun/modern-cpp-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
40 lines (34 loc) · 1.22 KB
/
main.cpp
File metadata and controls
40 lines (34 loc) · 1.22 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
#include <iostream> // std::cout, std::endl
#include <vector> // std::vector
#include <string> // std::string
#include <future> // std::future
#include <thread> // std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
#include "ThreadPool.hpp"
int main()
{
// create a thread pool with max. 4 concurrency threads
ThreadPool pool(4);
// create execution results list
std::vector< std::future<std::string> > results;
// start eight thread task
for(int i = 0; i < 8; ++i) {
// add all task to result list
results.emplace_back(
// ass print task to thread pool
pool.enqueue([i] {
std::cout << "hello " << i << std::endl;
// wait a sec when the previous line is out
std::this_thread::sleep_for(std::chrono::seconds(1));
// keep output and return the status of execution
std::cout << "world " << i << std::endl;
return std::string("---thread ") + std::to_string(i) + std::string(" finished.---");
})
);
}
// outputs
for(auto && result: results)
std::cout << result.get() << ' ';
std::cout << std::endl;
return 0;
}