C++简单线程池
obsidian link
# 实现了一个简单的线程池类
# 代码
ThreadPool.h
#ifndef _BPOOL_H__
#define _BPOOL_H__
#include <thread>
#include <mutex>
#include <vector>
#include <queue>
#include <functional>
#include <condition_variable>
class bpool
{
private:
/* data */
std::vector<std::thread> threads; // 储存线程池中的线程
std::queue<std::function<void()>> tasks; // 储存任务队列
std::mutex tasks_mtx; // 线程锁
std::condition_variable cv; //条件变量,让没有任务的线程进入等待状态
bool stop;
public:
bpool() = delete;
bpool(int num_threads);
~bpool();
void add_task(std::function<void()> task);
};
#endif
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
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
ThreadPool.cpp
#include "ThreadPool.h"
bpool::bpool(int num_threads) : stop(false)
{
for (int i = 0; i < num_threads; i++)
{
threads.emplace_back([this](){
while(true){
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(tasks_mtx);
cv.wait(lock, [this](){
return stop || !tasks.empty();
});
if(stop && tasks.empty()) return;
task = tasks.front();
tasks.pop();
}
task();
}
});
}
}
bpool::~bpool()
{
{
std::unique_lock<std::mutex> lock(tasks_mtx);
stop = true;
}
cv.notify_all(); // 唤醒所有等待的线程
for(auto &t : threads) // 结束所有线程
if (t.joinable())
{
t.join();
}
}
void add_task(std::function<void()> task)
{
{
std::unique_lock<std::mutex> lock(tasks_mtx);
if (stop)
{
throw std::runtime_error("bpool is stopped");
}
tasks.emplace(task);
}
cv.notify_one();
}
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
46
47
48
49
50
51
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
46
47
48
49
50
51
编辑 (opens new window)
上次更新: 2024/05/09, 12:51:17