手写线程池

​ 手写线程池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include<vector>
#include<string>
#include<list>
#include<thread>
#include<condition_variable>
using namespace std;
class ThreadPool {
public:
ThreadPool(int threadnum):started(false),thread_num(threadnum) {
//构造函数声明未启动和线程数量
}
~ThreadPool(){
//析构函数是停止,阻塞所有线程并将其从线程列表剔除后删除,清空线程列表。
stop();
for (int i = 0; i < thread_num; ++i) {
threadlist[i]->join();
}
for (int i = 0; i < thread_num; ++i) {
delete threadlist[i];
}
threadlist.clear(); //清空线程列表
}

void threadFunc(){}//线程执行函数,可自定义。
int getThreadNum() { return thread_num; }
void start() { //启动线程池函数,将num个线程绑定threadFunc自定义函数并执行,加入线程列表
if (thread_num > 0) {
started = true;
for (int i = 0; i < thread_num; ++i) {
thread* pthread = new thread(&threadFunc, this);
threadlist.push_back(pthread);
}
}
}
void stop() { //暂时停止线程,并由条件变量通知所有线程。
started = false;
condition.notify_all(); //用于唤醒所有等待条件变量的线程。
}

private:
int thread_num;
bool started;
vector<thread*> threadlist;
condition_variable condition;
};
-------------本文结束 感谢阅读-------------
0%