c++11 线程池系列之一 最简单的线程池

来源:互联网 发布:地狱之眼优化技能特效 编辑:程序博客网 时间:2024/06/14 16:57

线程池最简单的形式是含有一个固定数量的工作线程来处理任务,典型的数量是std::thread::hardware_concurrency().

当有任务要处理时,调用一个函数将任务放到等待队列中。每个工作线程都是从该队列中取出任务,执行完任务后继续从等待队列取出更多的任务来处理。在最简单的情况,没有办法来等待一个任务完成。如需要这样的功能,则需要用户自己维护同步。

下面上代码

class thread_pool{    std::atomic_bool done;    thread_safe_queue<std::function<void()> > work_queue;    std::vector<std::thread> threads;    join_threads joiner;    void worker_thread()    {        while(!done)        {            std::function<void()> task;            if(work_queue.try_pop(task))            {                task();            }            else            {                std::this_thread::yield();            }        }    }public:    thread_pool():        joiner(threads)    {done.store(false);        unsigned const thread_count=std::thread::hardware_concurrency();        try        {            for(unsigned i=0;i<thread_count;++i)            {                threads.push_back(                    std::thread(&thread_pool::worker_thread,this));            }        }        catch(...)        {            done=true;            throw;        }    }    ~thread_pool()    {        done=true;    }    template<typename FunctionType>    void submit(FunctionType f)    {        work_queue.push(std::function<void()>(f));    }};


其中jointhread与thread_safe_queue会在另一文章中单独给出

1 0
原创粉丝点击