简单的线程池 c++ 11
2016-08-12 18:27
134 查看
thread_pool.cpp
main.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(); }
相关文章推荐
- 使用C++ 11特性写一个简单的线程池
- c++ 11 多线线程系列-------- 一个最简单而且实用的线程池
- 【转】一个简单的线程池(c++版)
- 不到300行的简单线程池C++实现
- 使用C++实现简单线程池
- C++实现简单的线程池
- 【转】一个简单的线程池(c++版)
- C++ 简单的线程池 thread_pool
- [C++]_[线程池的简单实现]
- C++实现简单线程池
- c++编写简单线程池
- 简单C++线程池包装类源码示例
- C++线程池的简单实现方法
- c++简单线程池实现
- 一个C++基于boost简单实现的线程池
- Linux C++ 一个线程池的简单实现(附代码)
- 练习写C++代码(11)--实现简单的时钟类3
- 用c++实现的线程池,简单易懂
- C++ 11 for-range 访问容器简单实现
- 【C/C++开发】C++实现简单的线程池