C++ | 简单的使用 bind + function 实现一个简单的线程池(简单逻辑)

本文介绍了如何在C++中使用线程类Thread和ThreadPool来管理线程,通过bind函数将函数与线程绑定,创建线程池并执行任务。主要展示了线程的创建、封装和协同工作过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <thread>
using namespace placeholders;
//线程类
class Thread{
public:
    Thread(function<void(int)> func, int x):_func(func), _x(x){};
    ~Thread(){};
    thread start(){
        thread t(_func, _x);
        return t;
    }

private:
    function<void(int)> _func;
    int _x;

};

class ThreadPool{
public:
    ThreadPool(){};
    ~ThreadPool(){};


    //准备部分包括  将线程要执行的函数进行绑定,然后把线程类的start 封装到容器中  start 执行线程类的function 
    //简单来讲就是把要执行的函数封装到 线程 thread   等待thread执行
    //差点人傻了
    // thread t(func1, 参数...); 然后 t.join();         这就是创建线程 t 然后线程 t执行函数func1
    void parper(int n){
        for(int i = 0; i < n; ++i){
            _pool.push_back(new Thread(bind(&ThreadPool::function, this, _1), i));
        }

        for(int i = 0; i < n; ++i){
            _header.push_back(_pool[i]->start());
        }
    }
    void run(){
        for(thread &x : _header){
            x.join();
        }
    }

private:
    vector<Thread*> _pool;
    vector<thread> _header;

    //线程执行的函数
    void function(int id){
        cout<<"action and the id = "<<id<<endl;
    }

};

int main(){

    ThreadPool test;
    test.parper(10);
    test.run();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值