话不多说上代码,注视详细
thread_pool.h
#pragma once
#include<thread>
#include<mutex>
#include<windows.h>
#include<vector>
#include<queue>
//任务,包括任务执行的函数指针与所传参数
struct task {
public:
void (*task_callback)(void* arg);
void* params;
};
//线程池类
//包括初始化,加入任务,与停止线程池
class thread_pool {
public:
bool init(int nums);
bool add_task(task* item);
bool exit();
private:
std::vector<std::thread>thread_vec;//线程数组
std::queue<task*>task_que;//任务队列
bool terminate;//是否退出标志位
std::condition_variable m_condfun;//条件变量,加入任务后通知线程开始干活
std::mutex m_mutex;//互斥量,协调线程工作
void work();//线程在这里循环取任务
};
thread_pool.cpp
#include "thread_pool.h"
using namespace std;
void thread_pool::work() {
while (!terminate) {
unique_lock<mutex>lock1(m_mutex);
while (task_que.empty()) {
m_condfun.wait(lock1);
}
task* head = task_que.front();
task_que.pop();
lock1.unlock();
head->task_callback(head->params);
}
}
bool thread_pool::init(int nums) {
if (nums < 1)
return false;
terminate = false;
thread_vec.resize(nums);
for (int i = 0; i < nums; i++)
thread_vec[i] = thread(&thread_pool::work, this);
Sleep(1);
return true;
}
bool thread_pool::add_task(task* item) {
unique_lock<mutex>lock1(m_mutex);
task_que.push(item);
m_condfun.notify_one();
return true;
}
bool thread_pool::exit() {
terminate = true;
return true;
}
测试函数
main.cpp
#include"thread_pool.h"
#include<iostream>
using namespace std;
void p(void* i) {
int* a = (int*)i;
cout << "打印:" <<(int)*a << endl;
}
int main() {
task t1,t2;
int a = 1, b = 2;
t1.params = (void*)(&a);
t1.task_callback = *p;
t2.params = (void*)(&b);
t2.task_callback = *p;
thread_pool pool;
pool.init(2);
while (1) {
pool.add_task(&t1);
Sleep(50);
pool.add_task(&t2);
Sleep(50);
}
system("pause");
}
over!