BS_thread_pool 轻量级线程池

#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();
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值