C++thread

//
// Created by zgp on 2021/5/15.
//
#include <vector>
#include <deque>
#include <thread>
#include <functional>
#include <mutex>
#include <assert.h>
#include <condition_variable>
class thread_pool{
public:
    typedef std::function<void()> task_t;

    thread_pool(int init_size = 3);
    ~thread_pool();

    void stop();
    void add_task(const task_t&);  //thread safe;  //http://www.voidcn.com/article/p-vgunmvfe-ca.html

private:
    thread_pool(const thread_pool&);//禁止复制拷贝.
    const thread_pool& operator=(const thread_pool&);

    bool is_started() const { return m_is_started; }
    void start();

    void thread_loop();
    task_t take();

    typedef std::vector<std::thread*> threads_t;
    typedef std::deque<task_t> tasks_t;

    int m_init_threads_size;

    threads_t m_threads;
    tasks_t m_tasks;

    std::mutex m_mutex;
    std::condition_variable m_cond;
    bool m_is_started;
};
thread_pool::thread_pool(int init_size)
        :m_init_threads_size(init_size),
         m_mutex(),
         m_cond(),
         m_is_started(false)
{
    start();
}

thread_pool::~thread_pool()
{
    if(m_is_started)
    {
        stop();
    }
}

void thread_pool::start()
{
    assert(m_threads.empty());
    m_is_started = true;
    m_threads.reserve(m_init_threads_size);
    for (int i = 0; i < m_init_threads_size; ++i)
    {
        m_threads.push_back(new std::thread(std::bind(&thread_pool::thread_loop, this)));
    }

}

void thread_pool::stop()
{
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_is_started = false;
        m_cond.notify_all();
    }

    for (threads_t::iterator it = m_threads.begin(); it != m_threads.end() ; ++it)
    {
        (*it)->join();
        delete *it;
    }
    m_threads.clear();
}


void thread_pool::thread_loop()
{
    while(m_is_started)
    {
        task_t task = take();
        if(task)
        {
            task();
        }
    }
}

void thread_pool::add_task(const task_t& task)
{
    std::unique_lock<std::mutex> lock(m_mutex);
    m_tasks.push_back(task);
    m_cond.notify_one();
}

thread_pool::task_t thread_pool::take()
{
    std::unique_lock<std::mutex> lock(m_mutex);
    //always use a while-loop, due to spurious wakeup
    while(m_tasks.empty() && m_is_started)
    {
        m_cond.wait(lock);
    }


    task_t task;
    tasks_t::size_type size = m_tasks.size();
    if(!m_tasks.empty() && m_is_started)
    {
        task = m_tasks.front();
        m_tasks.pop_front();
        assert(size - 1 == m_tasks.size());
        /*if (TaskQueueSize_ > 0)
        {
          cond2.notify_one();
        }*/
    }

    return task;

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值