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

【c++11 新特性应用】利用bind实现通用的混合任务线程池

2017-07-05 22:51 459 查看
先简单认识一下std::bind,详细资料查阅相关资料,这里不啰嗦,假设你已经具备了理论知识:

auto f1 = bind(&fun_int, 3,std::placeholders::_1);

这名话的意思是给fun_int绑定2个参数,第一个是3,第二个本来的第1个参数,返回一个函数对象,这样调用f1(5) 等价于调用fun_int(3,5)

这样,bind就可以将任意函数的任意具体调用,生成一个指定的调用方式,比如无参调用,这样线程池只需要维护类型是std::function<void()>类型的对象即可。

具体实现如下,3个文件,ThreadPool.cpp  ThreadPool.h,main.cpp是测试文件。condition_variable之前没有用过,用的都是linux c标准的,这里现学现用,可能用bug,复核后再参考。

ThreadPool.h

#pragma once
#include <functional>
#include <vector>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
using namespace std;

typedef function<void()> TaskType;
class ThreadPool
{
mutex m_mtx;
condition_variable m_cv;
bool m_running = true;
vector<thread> m_threads;
//
queue<TaskType> m_tasks;
void Run(int id);
public:
//初始化,自动启用线程
ThreadPool(int tnum);
//析构,终止
~ThreadPool();
//添加一个任务
bool AddTask(TaskType task);
//终止线程池,消化完所有任务
void Stop();
};

ThreadPool.cpp

#include <iostream>
#include "ThreadPool.h"

ThreadPool::ThreadPool(int tnum)
{
//初始化放在线程初始化之前
for(int i = 0; i < tnum; i++)
m_threads.push_back(thread(&ThreadPool::Run, this, i));
}

ThreadPool::~ThreadPool()
{
Stop();
}

void ThreadPool::Run(int id)
{
while(true)
{
unique_lock<mutex> lck(m_mtx);
while(m_tasks.empty())
{
if(!m_running)
{
cout << "----thread end " << id << endl;
return;
}
m_cv.wait(lck);
}
//
cout << "----deal task " << id << endl;
auto t = m_tasks.front();
m_tasks.pop();
t();
}
}

void ThreadPool::Stop()
{
cout << "----Stop" << endl;
m_running = false;
while(!m_tasks.empty()) //消化完队列再终止
{
unique_lock<mutex> lck(m_mtx);
m_cv.notify_all();
}
m_mtx.lock(); //这里不可以使用unique_lock<mutex>,释放时机晚于join,形成死锁
m_cv.notify_all();
m_mtx.unlock();
for(auto& item : m_threads)
item.join();
m_threads.clear();
}

bool ThreadPool::AddTask(TaskType task)
{
cout << "----push taks" << endl;
unique_lock<mutex> lck(m_mtx);
m_tasks.push(task);
m_cv.notify_one();
return true;
}


main.cpp
#include <string>
#include <iostream>
#include "ThreadPool.h"
using namespace std;

class Obj
{
int m_val;
public:
Obj(int val) : m_val(val) {}
void DisPlay()
{
cout << "DisPlay: " << m_val << endl;
}
};

void fun_int(int a)
{
cout << "fun int " << a << endl;
}

void fun_string(string a, int max)
{
cout << "fun string " << a.length() << " " << max << endl;
}

int main()
{
auto f1 = bind(&fun_int, 3);
auto f2 = bind(&fun_int, 5);
auto f3 = bind(&fun_string, "test", 1);
auto f4 = bind(&Obj::DisPlay, Obj(11));
function<void()> f5 = bind(&Obj::DisPlay, Obj(22));
//
ThreadPool pool(3);
pool.AddTask(f1);
pool.AddTask(f2);
pool.AddTask(f3);
pool.AddTask(f4);
pool.AddTask(f5);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐