0%

线程池

什么是线程池

线程池是一种线程管理模式,预先创建固定数量的线程,任务通过队列分配给空闲线程执行。

线程池的作用:

  • 减少线程创建和销毁的开销,适合短任务频繁执行。
  • 控制并发数量,防止系统过载。
  • 避免占用当前线程,在线程池中异步执行任务。
  • 提高资源利用率,优化性能。

单消费者单生产者线程池

上图中,可以发现线程池其实主要包括三个部分:任务队列,生产者线程、消费者线程。

而对于上图中这样的单任务队列线程池来说,生产者和消费者的公共资源只有一个(单个任务队列),这也导致了线程池并发上就是经典的生产者-消费者模型。即同时只能有一个生产者或一个消费者访问公共资源。

此外,由于线程池中线程数量固定,且线程是可复用。不用频繁创建和销毁。

而对于上图中这样的单任务队列线程池来说,生产者和消费者的公共资源只有一个(单个任务队列),这也导致了线程池并发上就是经典的生产者-消费者模型。即同时只能有一个生产者或一个消费者访问公共资源。

此外,由于线程池中线程数量固定,且线程是可复用。不用频繁创建和销毁。

⚠️注:

  • 任务队列其实和消息队列设计是同理的。而且两者的功能也是类似(缓冲+高并发)
  • 此外,任务队列的状态也决定了消费者线程的状态,即任务队列为空时,消费者线程应该阻塞。但是如果一直没有任务进入队列,也不应该让消费者线程一直阻塞,所以还需要提供一个解除所有阻塞在任务队列中的消费者线程的接口。

阻塞队列代码如下:

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
//这里队列的大小都没有设置上限
template <typename T>
class BlockingQueue {
public:
// 队列默认阻塞消费者线程
BlockingQueue(bool nonblock = false) : nonblock_(nonblock) {}
~BlockingQueue() {}

// 入队
void push(const T& task) { //这里task使用const是为了不修改传入的参数
std::lock_guard<std::mutex> lck(mtx);
que_.push(task);
not_empty.notify_one(); //通知一个等待的线程
}

// 出队,这里添加返回值检验是因为队列可能为空
bool pop(T& task) {
std::unique_lock<std::mutex> lck(mtx);
not_empty.wait(lck, [this]() {
return !que_.empty() || nonblock_;
});
if (que_.empty()) {
return false;
}
task = que_.front();
que_.pop();
return true;
}

// 解除阻塞在当前队列的线程
void cancel() {
std::lock_guard<std::mutex> lck(mtx);
nonblock_ = true;
not_empty.notify_all();
}
private:
bool nonblock_;
std::queue<T> que_;
std::mutex mtx;
std::condition_variable not_empty;
};

线程池的代码和下面多生产者多消费者里面的一样。

多生产者多消费者线程池

​ 如上图所示,原来单任务队列的情况下,生产者线程和消费者线程都以任务队列作为公共资源,所以他们会发生碰撞,因此必须共用一个锁。现在生产者单独用一个队列,消费者单独用一个队列。这样只有生产者或消费者之间会发生碰撞,确保了可以同时存在生产者和消费者进行工作(这里实现的就是并行),而多个生产者/消费者之间就是并发。

​ 但是这里也有一个例外,即当消费者队列为空的时候,需要将生产者队列中任务交换到消费者队列中。而这个交换的过程中生产者线程和消费者线程就会发生碰撞。所以交换的过程中需要加一个生产者锁保护生产者队列的一致性。

这个设计思路又有那句“一个中间件不行就再加一个中间件的精髓了。

  • 阻塞队列代码如下:
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
template <typename T>
class BlockingQueuePro {
public:
BlockingQueuePro(bool nonblock = false) : nonblcok_(nonblock) {}
~BlockingQueuePro() {}

// 入队
void push(const T& task) {
std::lock_guard<std::mutex> lck(producer_mtx);
producer_que.push(task);
not_empty.notify_one(); //这里是通知交换过程中阻塞的消费者线程
}

// 出队,如果返回false那就走优雅的退出逻辑了
bool pop(T& task) {
std::lock_guard<std::mutex> lck(consumer_mtx);
if (consumer_que.empty() && swapQue() == 0) {
return false; //返回false的原因就是为生产者队列为空,而在条件变量not_empty作用下只有调用了cancel才会直接返回空。
}
task = consumer_que.front();
consumer_que.pop();
return true;
}

void cancel() {
std::lock_guard<std::mutex> lck(producer_mtx); //nonblock阻塞在生产者队列
nonblcok_ = true;
not_empty.notify_all();
}
private:
int swapQue() {
std::unique_lock<std::mutex> lck(producer_mtx);
not_empty.wait(lck, [this]() {
return !producer_que.empty() || nonblcok_; //只有这里会一直阻塞所以nonblock_就设置在这
});
swap(producer_que, consumer_que);
return consumer_que.size(); //返回0说明生产者队列也为空,这种情况只有nonblock为true才成立
}
private:
bool nonblcok_;
std::mutex producer_mtx;
std::mutex consumer_mtx;
std::condition_variable not_empty;
std::queue<std::function<void()>> producer_que;
std::queue<std::function<void()>> consumer_que;
};
  • 线程池代码如下:
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
class ThreadPool {
public:
ThreadPool(int threadNum) {
for (int i = 0; i < threadNum; ++i) {
workers.emplace_back([this]() { //要将一个类的成员函数作为thread的线程入口函数传递需要this指针或者声明为static,否则就会报错。这里用lambda巧妙解决了问题
this->worker();
});
}
}

~ThreadPool() {
taskQueue.cancel();
for (auto &worker: workers) {
//释放线程
if (worker.joinable()) {
worker.join();
}
}
};

// 提供给生产者线程,将任务加入队列
// typename... Args这种写法为可变参数模版,表示接受一组参数. ...为展开类型包
template<typename F, typename... Args>
void enqueue(F &&f, Args &&...args) {
std::function<void()> task = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
taskQueue.push(task);
}
private:
// 消费者线程
void worker() {
while(true) {
std::function<void()> task;
if (!taskQueue.pop(task)) {
break; //终止
}
task();
}
}

private:
// 这里任务使用std::function<void()来进行包装,但是只能接受void()的,所以需要使用std::bind来做函数适配,确保任务队列可以接受任何类型的函数.
// std::bind作用就是绑定函数签名和参数并生成一个新的可调用对象。
// BlockingQueue<std::function<void()>> taskQueue;
BlockingQueuePro<std::function<void()>> taskQueue;
std::vector<std::thread> workers;
};
  • 测试用例如下:
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
#include <mutex>

#include "threadPool_V2.h"

// 统计任务完成的数量
std::atomic<int> taskCounter{0};
// 序列化标准输出,避免多线程下的日志串行冲突
std::mutex cout_mtx;

// 任务
void task(int id) {
std::this_thread::sleep_for(std::chrono::milliseconds(100)); //模拟任务执行的时间
std::lock_guard<std::mutex> lock(cout_mtx);
std::cout << "Task " << id << " excuted by thread " << std::this_thread::get_id() << std::endl;
taskCounter++;
}

// 生产者线程入口函数
void producer(ThreadPool& pool, int producer_id, int num_tasks) {
for (int i = 0; i < num_tasks; ++i) {
int task_id = producer_id * 1000 + i;
pool.enqueue(task, task_id); //enqueue第二个参数往后就是task函数的参数了
{
std::lock_guard<std::mutex> lock(cout_mtx);
std::cout << "Producer " << producer_id << " enqueued task " << task_id << std::endl;
}
}
}

int main() {
const int n_producers = 4; //生产者线程数量
const int n_tasks_per_producer = 10; //生产者提交的任务数量
const int num_threads_in_pool = 2; // 线程池中的工作线程数量

auto start = std::chrono::steady_clock::now();
ThreadPool pool(num_threads_in_pool);

std::vector<std::thread> producers;

// 启动生产者线程
for (int i = 0; i < n_producers; ++i) {
producers.emplace_back(producer, std::ref(pool), i, n_tasks_per_producer); // 这里为什么要用std::ref??
}

// 等待生产者线程完成
for (auto& producer : producers) {
producer.join();
}

// 等待所有任务完成
while (taskCounter < n_producers * n_tasks_per_producer) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

auto end = std::chrono::steady_clock::now();
auto elapsed_ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();

std::cout << "all tasks have completed! taskCount: " << taskCounter << std::endl;
std::cout << "elapsed: " << elapsed_ms << " ms" << std::endl;
return 0;

}