什么是线程池
线程池是一种线程管理模式,预先创建固定数量的线程,任务通过队列分配给空闲线程执行。
线程池的作用:
- 减少线程创建和销毁的开销,适合短任务频繁执行。
- 控制并发数量,防止系统过载。
- 避免占用当前线程,在线程池中异步执行任务。
- 提高资源利用率,优化性能。
单消费者单生产者线程池
上图中,可以发现线程池其实主要包括三个部分:任务队列,生产者线程、消费者线程。
而对于上图中这样的单任务队列线程池来说,生产者和消费者的公共资源只有一个(单个任务队列),这也导致了线程池并发上就是经典的生产者-消费者模型。即同时只能有一个生产者或一个消费者访问公共资源。
此外,由于线程池中线程数量固定,且线程是可复用。不用频繁创建和销毁。
而对于上图中这样的单任务队列线程池来说,生产者和消费者的公共资源只有一个(单个任务队列),这也导致了线程池并发上就是经典的生产者-消费者模型。即同时只能有一个生产者或一个消费者访问公共资源。
此外,由于线程池中线程数量固定,且线程是可复用。不用频繁创建和销毁。
⚠️注:
- 任务队列其实和消息队列设计是同理的。而且两者的功能也是类似(缓冲+高并发)
- 此外,任务队列的状态也决定了消费者线程的状态,即任务队列为空时,消费者线程应该阻塞。但是如果一直没有任务进入队列,也不应该让消费者线程一直阻塞,所以还需要提供一个解除所有阻塞在任务队列中的消费者线程的接口。
阻塞队列代码如下:
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) { 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(); }
bool pop(T& task) { std::lock_guard<std::mutex> lck(consumer_mtx); if (consumer_que.empty() && swapQue() == 0) { return false; } task = consumer_que.front(); consumer_que.pop(); return true; }
void cancel() { std::lock_guard<std::mutex> lck(producer_mtx); 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_; }); swap(producer_que, consumer_que); return consumer_que.size(); } 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]() { this->worker(); }); } }
~ThreadPool() { taskQueue.cancel(); for (auto &worker: workers) { if (worker.joinable()) { worker.join(); } } };
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: 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); { 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); }
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;
}
|