#include "BS_thread_pool.hpp"
#include<Windows.h>
int testBS()
{
BS::thread_pool pool; // 创建线程池,默认线程数为硬件支持的并发数
pool.get_thread_count();
pool.get_tasks_total();
auto task = [] { Sleep(100); std::cout << "1" << std::endl; };
auto task2 = [] { std::cout << "2" << std::endl; };
auto task3 = [] { std::cout << "3" << std::endl; };
pool.submit_task(task);
pool.submit_task(task2);
pool.submit_task(task3);
return 0;
}
void testBS2()
{
BS::thread_pool pool;
std::future<int> my_future1 = pool.submit_task([] { return 1; });
std::future<int> my_future2 = pool.submit_task([] { return 2; });
std::future<int> my_future3 = pool.submit_task([] {Sleep(5000); return 3; });
int a = 0;
pool.wait(); //等待所有任务完成
int a2 = my_future2.get();
int a3 = my_future3.get();
int a1= my_future1.get();
int xx = 0;
}
int testBS3() {
// 创建线程池,默认线程数为硬件支持的并发数
BS::thread_pool pool;
// 提交一些任务并获取 future 对象
std::vector<std::future<int>> futures;
for (int i = 0; i < 10; ++i) {
// 使用 push_task 提交任务,并返回 future
auto future = pool.submit_task([i] {
std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟耗时任务
std::cout << "Task " << i << " completed by thread "
<< std::this_thread::get_id() << std::endl;
return i * 2; // 返回任务结果
});
futures.push_back(std::move(future)); // 将 future 存入容器
}
std::cout << "All tasks submitted. Waiting for tasks to complete..." << std::endl;
// 等待所有任务完成
pool.wait();
// 获取任务结果
for (size_t i = 0; i < futures.size(); ++i) {
std::cout << "Result of task " << i << ": " << futures[i].get() << std::endl;
}
std::cout << "All tasks completed. Exiting program." << std::endl;
return 0;
}
int main()
{
testBS2();
testBS();
getchar();
}
BS_thread_pool 轻量级线程池
于 2025-03-17 11:21:18 首次发布