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

c++11 线程池实现

2020-02-01 11:21 836 查看

#ifndef THREAD_POOL_H
#define THREAD_POOL_H
ThreadPool.h
#include <thread>
#include <thread>
#include <condition_variable>
#include <functional>
#include <vector>
#include <queue>
using namespace std;
class ThreadPool
{
public:
using Task = std::function<void()>;
explicit ThreadPool(int num): _thread_num(num), _is_running(false) {}
~ThreadPool() {
if (_is_running)
stop();
}
void start() {
_is_running = true;
// start threads
for (int i = 0; i < _thread_num; i++)
_threads.emplace_back(std::thread(&ThreadPool::work, this));
}
void stop()
{
{
// stop thread pool, should notify all threads to wake
std::unique_lock<std::mutex> lk(_mtx);
_is_running = false;
_cond.notify_all(); // must do this to avoid thread block
}
// terminate every thread job
for (auto& t : _threads){
if (t.joinable())
t.join();
}
}
void appendTask(const Task& task)
{
if (_is_running) {
std::unique_lock<std::mutex> lk(_mtx);
_tasks.push(task);
_cond.notify_one(); // wake a thread to to the task
}
}
private:
void work()
{
cout<<“begin work thread: %d\n”, std::this_thread::get_id();
while (_is_running||!_threads.empty())
{
Task task;
{
std::unique_lock<std::mutex>lk(_mtx);
if (!_tasks.empty()) {
task = _tasks.front();
_tasks.pop(); // remove the task
_cond.notify_one();
}
else{
_cond.wait(lk);
}
}
if (task)
task(); // do the task
}
cout<<“end work thread: %d\n”, std::this_thread::get_id();
}
public:
// disable copy and assign construct
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool& other) = delete;
private:
bool _is_running; // thread pool manager status
std::mutex _mtx;
std::condition_variable _cond;
int _thread_num;
std::vector<std::thread>_threads;
std::queue<Task>_tasks;
};
#endif //

main.cpp
#include “ThreadPool.h”
void fun1()
{
std::cout << "working in thread " << std::this_thread::get_id() << std::endl;
}
void fun2(int x)
{
std::cout << "task " << x << " working in thread " << std::this_thread::get_id() << std::endl;
}
int main(int argc, char* argv[])
{
ThreadPool thread_pool(3);
thread_pool.start();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
for (int i = 0; i < 6; i++) {
//thread_pool.appendTask(fun1);
thread_pool.appendTask(std::bind(fun2, i));
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
thread_pool.stop();
return 0;
}

  • 点赞
  • 收藏
  • 分享
  • 文章举报
来自北方的小白 发布了3 篇原创文章 · 获赞 0 · 访问量 28 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: