包含两个队列,一个任务队列和一个线程队列。启动线程池前首先创建任务,将所有任务加入任务队列。
头文件thread_pool.h:
#pragma once
#include<condition_variable>
#include<mutex>
#include<vector>
#include<thread>
#include<deque>
#include<chrono>
#include<iostream>
typedef void (*RUNFUC)(void);
/* 任务函数 */
class thread_pool
{
public:
thread_pool(int t_size=3);
~thread_pool();
void start();
void stop();
void add_task(void *in_task);
void set_size(int t_size){t_size=t_size;};
void do_task();
bool is_stopped() {return is_stop;};
void join();
protected:
private:
std::deque<RUNFUC> task;
std::vector<std::thread *> t_list;
std::vector<void *> runfuc_args;
int t_size;
std::mutex m;
std::condition_variable t_not_full, t_not_empty;
std::condition_variable task_not_full, task_not_empty;
bool is_stop;
};
cxx文件thread_pool.cxx:
#include"thread_pool.h"
thread_pool::thread_pool(int t_size) : t_size(t_size), is_stop(false)
{
}
thread_pool::~thread_pool()
{
if (!is_stopped())
stop();
}
void thread_pool::start()
{
for(int i=0; i<t_size; ++i)
{
t_list.push_back(new std::thread(&thread_pool::do_task, this));
}
}
void thread_pool::join()
{
for (int i=0; i<t_size;++i)
(*t_list.at(i)).join();
std::cout << "join finished\n";
}
void thread_pool::stop()
{
is_stop = true;
for (int i=0; i<t_size; ++i)
delete t_list.at(i);
std::cout << "delete finished\n";
}
void thread_pool::do_task()
{
while (!is_stop && !task.empty())
{
std::unique_lock<std::mutex> lck(m);
while (task.empty())
{
task_not_empty.wait(lck);
}
auto t_task = task.front();
task.pop_front();
lck.unlock();
t_task();
}
}
void thread_pool::add_task(void *in_task)
{
std::unique_lock<std::mutex> lck(m);
task.push_back((RUNFUC)in_task);
if (task.size() == 1)
task_not_empty.notify_one();
}
测试文件pooltest.cxx:
#include<iostream>
#include<thread>
#include<ctime>
#include"thread_pool.h"
void task_1(void)
{
std::cout << "Thread id : " <<
std::this_thread::get_id() << "\t do task\n";
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
int main(void)
{
int t_size, task_size;
std::cout << "Pleaes input the numbers of threads and tasks you want to create:\n";
std::cin >> t_size >> task_size;
thread_pool *pool = new thread_pool(t_size);
for (int i=0; i<task_size; ++i)
{
pool->add_task((void *)task_1);
}
clock_t begin = clock();
pool->start();
pool->join();
clock_t end = clock();
std::cout << "Time used : " << (end-begin)/CLOCKS_PER_SEC << " s\n";
delete pool;
return EXIT_SUCCESS;
}
使用g++进行编译和运行结果: