Boost库实现线程池实例

#ifndef MY_TASK_QUEUE_H
#define	MY_TASK_QUEUE_H
#include <queue>
#include <boost/thread.hpp>
#include <boost/noncopyable.hpp>
#include <boost/function.hpp>
//using namespace boost;
//using namespace std;
typedef boost::function<void(void)> my_task;
//任务队列
class Task_queue:boost::noncopyable
{
private:
    std::queue<my_task> my_queue;
    boost::condition_variable_any cond;
    boost::mutex my_mutex;
public:
    void push_task(const my_task & task_func)
    {  //加上互斥锁
        boost::unique_lock<boost::mutex> lock(my_mutex);
        my_queue.push(task_func);
        //通知其他线程启动
        cond.notify_one();
    }
    my_task get_task(){
        //加上互斥锁
        boost::unique_lock<boost::mutex> lock(my_mutex);
        if(my_queue.size()==0)
        {
            //如果队列中没有任务,则等待互斥锁
            cond.wait(lock);
        }
        //指向队列首部
        my_task task(my_queue.front());
        //出队列
        my_queue.pop();
        return task;      
    }
    int get_size()
    {
        return my_queue.size();
    }
};

#endif	

#ifndef MY_THREAD_POOL_H
#define	MY_THREAD_POOL_H
#include <boost/thread.hpp>
#include <boost/noncopyable.hpp>
#include <boost/function.hpp>
#include "My_Task_queue.h"
#include <iostream>
using namespace std;
class My_thread_pool:boost::noncopyable
{
private:
    //线程队列
    Task_queue my_queue;
    //线程组
    boost::thread_group my_thread_group;
    int thread_num;
    volatile bool is_run;
    void run()
    {
        while(is_run)
        {
            cout<<"run "<<endl;
            //一直处理线程池的任务
            my_task task=my_queue.get_task();
            task();
        }
    }
public:
    My_thread_pool(int num):thread_num(num),is_run(false)
    {
        
    };
    ~My_thread_pool(){
    
    };
    void init()
    {
        is_run=true;
        if(thread_num<=0)
        {
            return ;
        }
        for(int i=0;i<thread_num;++i)
        {
            //生成多个线程,绑定run函数,添加到线程组
            my_thread_group.add_thread(new boost::thread(boost::bind(&My_thread_pool::run,this)));
        }
    }
    //停止线程池
    void stop()
    {
        is_run=false;
    }
    //添加任务 
    void post(const my_task &task)
    {
        my_queue.push_task(task);
    }
    void wait()
    {
        my_thread_group.join_all();
    }
              
};
#endif	

#include "My_Task_queue.h"
#include "My_thread_pool.h"
#include <iostream>
#include <cstdlib>
using namespace std;

void print_task(int i)
{
    cout<<"I am Task "<<i<<" number:"<<endl;
}
//使用boost线程池  编译参数加上-lboost_thread
int main(int argc, char** argv) {

    My_thread_pool tp(4);
    tp.init();
    
    my_task task[4];
    for(int i=0;i<4;i++)
    {
        //生成线程任务,类型为函数指针 boost::function<void(void)>
        task[i]=boost::bind(print_task,i+1);
        //放到线程池中处理
        tp.post(task[i]);
    }
    //等待线程池处理完成!
   tp.wait();
    
    return 0;
}





你可能感兴趣的:(Boost库实现线程池实例)