forked from progschj/ThreadPool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.cpp
More file actions
36 lines (31 loc) · 1 KB
/
Copy pathexample.cpp
File metadata and controls
36 lines (31 loc) · 1 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
#include <iostream>
#include <vector>
#include <chrono>
#include "ThreadPool.h"
int main()
{
// 创建线程池,里面有四个工作线程
ThreadPool pool(4);
// 通过future拿到每个工作线程运行完的结果,保存在results中
std::vector< std::future<int> > results;
// 将8个任务压入任务队列,线程池中的四个工作线程会不断地取任务
// 任务执行完的结果压入results容器中
// 8个任务函数是通过lambda表达式来实现的
for (int i = 0; i < 8; ++i) {
results.emplace_back(
pool.enqueue([i] {
std::cout << "hello " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "world " << i << std::endl;
return i * i;
})
);
//std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
// 打印8个任务的结果
for (auto && result : results)
std::cout << result.get() << ' ';
std::cout << std::endl;
system("pause"); // 如果不是采用的VS编译器,注释该行
return 0;
}