先簡單認識一下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;
}