您的位置:首页 > 编程语言 > C语言/C++

简单的线程池 c++ 11

2016-08-12 18:27 134 查看
thread_pool.cpp

#include "thread_pool.h"

namespace wang
{

wthread_pool::wthread_pool() : m_stop{ false }
{

}

wthread_pool::~wthread_pool()
{
shutdown();
}

void wthread_pool::start(size_t size)
{
size = size < 1 ? 1 : size;
m_threads.reserve(size);
for (size_t i = 0; i < size; ++i)
{
m_threads.emplace_back(&wthread_pool::schedual, this);    // push_back(std::thread{...})
}
}

void wthread_pool::post_task(wTask task)
{
if (m_stop.load())
{
return;
}

// 添加任务到队列
{
std::lock_guard<std::mutex> lock(m_lock);
m_tasks.push(task);
}
m_condition.notify_one();    // 唤醒线程执行
}

void wthread_pool::shutdown()
{
if (m_stop.load())
{
return;
}
m_stop.store(true);
m_condition.notify_all();
for (std::thread& thread : m_threads)
{
if (thread.joinable())
{
thread.join();
}
}
m_threads.clear();
}

// 任务调度
void wthread_pool::schedual()
{
wTask task;
while (true)
{
//get task
task = NULL;
{
std::unique_lock<std::mutex> lock{ m_lock };
if (m_tasks.empty())
{
m_condition.wait(lock, [this]() { return !m_tasks.empty() || m_stop.load(); });
if (m_tasks.empty())
{
std::cout << "thread " << std::this_thread::get_id() << " end" << std::endl;
break;
}
}
task = m_tasks.front();    // 取一个 task
m_tasks.pop();
}
if (task)
{
task();
}
}
}
}


main.cpp

#include <iostream>
#include <string>
#include "thread_pool.h"

void f()
{
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "hello, i am f" << std::endl;
}

struct H {

int test(int a)
{
std::this_thread::sleep_for(std::chrono::seconds(4));
std::cout << "hello, i am H's test !" << std::endl;
return 1;
}
};

int main()
{
wang::wthread_pool executor;
executor.start(10);

executor.post_task(f);

H ht;
executor.post_task(std::bind(&H::test, &ht, 1));

executor.shutdown();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息