使用bind与function模板创建线程池

上一篇博客中,我们讲解了function模版与std::bind,如下

c++可调用对象、function类模板与std::bind-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/qq_58158950/article/details/135590153?spm=1001.2014.3001.5501

今天我们使用这两个模版来模仿muduo网络库实现一个微型线程池 

#include<iostream>
#include<functional>
#include<vector>
#include<thread>
using namespace std;
using namespace placeholders;

class Thread
{
public:
    Thread(function<void()> func):_func(func){}
    //创建线程函数
    thread start()
    {
        return thread(_func);
    }
private:
    function<void()> _func;//已经被绑定过的线程执行函数
};

class ThreadPool
{
public:
    ThreadPool(){}

    virtual ~ThreadPool(){
        for(int i=0;i<_pool.size();i++)
            delete _pool[i];
    }

    //开启线程池
    void startPool(int size)
    {
        //将线程执行函数添加到线程对象中
        for(int i=0;i<size;i++)
        {
            _pool.push_back(
                //使用bind器直接将执行函数绑定到thread对象里
                new Thread(bind(&ThreadPool::runInThread,this,i))
                );
        }

        //创建线程池中的线程
        for(int i=0;i<size;i++)
        {
            _header.push_back(_pool[i]->start());
        }

        //等待所有子线程结束
        for(thread &t:_header)
        {
            t.join();
        }
    }
private:
    vector<Thread*> _pool;//线程池
    vector<thread> _header;//用于保存已经创建成功的线程对象

    //充当一个线程执行函数
    void runInThread(int id)
    {
        cout<<"call runInTHread id is "<<id<<endl;
    }
};

void test()
{
    ThreadPool pool;//定义线程池对象
    pool.startPool(10);//在线程池中创建10个线程
}
int main()
{
    test();
    return 0;
}

  • 13
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值