-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
79 lines (67 loc) · 2.36 KB
/
main.cpp
File metadata and controls
79 lines (67 loc) · 2.36 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
#include <iostream>
#include <chrono>
#include "ThreadPool.h"
// 示例1: 普通函数任务
int add(int a, int b) {
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟耗时操作
return a + b;
}
// 示例2: Lambda表达式
auto multiply = [](double a, double b) {
std::this_thread::sleep_for(std::chrono::milliseconds(150));
return a * b;
};
// 示例3: 带异常处理的任务
void might_throw(int x) {
if (x < 0) {
throw std::invalid_argument("Negative number not allowed");
}
std::cout << "Processing: " << x << std::endl;
}
int main() {
// 创建线程池,线程数设为硬件并发数
ThreadPool pool(std::thread::hardware_concurrency());
// 1、测试普通函数
std::vector<std::future<int>> results;
// 提交多个任务
for (int i = 0; i < 8; ++i) {
// 使用submit方法提交任务,获取future对象
auto future = pool.submit(add, i, i * 2);
results.push_back(std::move(future));
}
// 获取任务结果
for (size_t i = 0; i < results.size(); ++i) {
try {
int result = results[i].get(); // 阻塞直到结果就绪
std::cout << "Task " << i << " result: " << result << std::endl;
} catch (const std::exception& e) {
std::cerr << "Task " << i << " failed: " << e.what() << std::endl;
}
}
// 2、测试Lambda表达式
std::vector<std::future<double>> results2;
// 提交多个任务
for (int i = 0; i < 8; ++i) {
// 使用submit方法提交任务,获取future对象
auto future = pool.submit(multiply, i, i);
results2.push_back(std::move(future));
}
// 获取任务结果
for (size_t i = 0; i < results2.size(); ++i) {
try {
int result = results2[i].get(); // 阻塞直到结果就绪
std::cout << "Lambda Task " << i << " result: " << result << std::endl;
} catch (const std::exception& e) {
std::cerr << "Lambda Task " << i << " failed: " << e.what() << std::endl;
}
}
// 3、测试异常处理
try {
auto bad_future = pool.submit(might_throw, -5);
bad_future.get();
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
// 线程池会在析构时自动关闭
return 0;
}