C++ 入门第25天:线程池(Thread Pool)基础

该文章已生成可运行项目,

往期回顾:

C++ 学习第22天:智能指针与异常处理-优快云博客

C++ 入门第23天:Lambda 表达式与标准库算法入门-优快云博客

C++ 入门第24天:C++11 多线程基础-优快云博客


 C++ 入门第25天:线程池(Thread Pool)基础

前言

线程池 是一种高效的线程管理机制,通过复用一组线程来处理多个任务,避免频繁创建和销毁线程的开销。线程池在高并发场景中尤为重要,是现代程序开发中提升性能和资源利用率的重要工具。

今天,我们将学习线程池的基础知识,并实现一个简单的线程池。


1. 什么是线程池?

线程池的核心思想是提前创建一组线程,将任务放入队列中,线程从队列中取出任务并执行。当任务完成后,线程不会销毁,而是返回池中等待下一个任务。

线程池的优点

  1. 降低线程创建和销毁的开销。
  2. 控制线程的并发数量,避免资源过度消耗。
  3. 提高任务处理效率。

2. 线程池的基本结构

线程池的实现主要包括以下几个部分:

  1. 任务队列:存储需要执行的任务。
  2. 工作线程:从任务队列中取出任务并执行。
  3. 任务提交接口:提供给用户提交任务的功能。

3. 使用 std::async 实现简单线程池

std::async 是 C++11 提供的一种异步任务工具,可以用来实现简单的线程池。

示例代码

#include <iostream>
#include <future>
#include <vector>
using namespace std;

// 一个简单的任务函数
int task(int n) {
    cout << "Task " << n << " is running in thread " << this_thread::get_id() << endl;
    return n * n;
}

int main() {
    // 存储 future 对象的容器
    vector<future<int>> results;

    // 提交多个任务
    for (int i = 1; i <= 5; i++) {
        results.push_back(async(launch::async, task, i));
    }

    // 获取任务的执行结果
    for (auto &result : results) {
        cout << "Result: " << result.get() << endl;
    }

    return 0;
}

输出结果(线程 ID 可能不同):

Task 1 is running in thread 12345
Task 2 is running in thread 12346
Task 3 is running in thread 12347
Task 4 is running in thread 12348
Task 5 is running in thread 12349
Result: 1
Result: 4
Result: 9
Result: 16
Result: 25

4. 手动实现线程池

为了更深入理解线程池,我们可以手动实现一个简单的线程池。

4.1 线程池的代码实现

#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
using namespace std;

class ThreadPool {
public:
    ThreadPool(size_t num_threads);
    ~ThreadPool();

    // 提交任务到线程池
    template <class F, class... Args>
    auto enqueue(F&& f, Args&&... args) -> future<typename result_of<F(Args...)>::type>;

private:
    vector<thread> workers;             // 工作线程
    queue<function<void()>> tasks;      // 任务队列
    mutex queue_mutex;                  // 互斥锁
    condition_variable condition;       // 条件变量
    bool stop;                          // 停止标志
};

// 构造函数:创建指定数量的线程
ThreadPool::ThreadPool(size_t num_threads) : stop(false) {
    for (size_t i = 0; i < num_threads; ++i) {
        workers.emplace_back([this] {
            while (true) {
                function<void()> task;
                {
                    unique_lock<mutex> lock(this->queue_mutex);
                    this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
                    if (this->stop && this->tasks.empty()) return;
                    task = move(this->tasks.front());
                    this->tasks.pop();
                }
                task();
            }
        });
    }
}

// 提交任务到线程池
template <class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) -> future<typename result_of<F(Args...)>::type> {
    using return_type = typename result_of<F(Args...)>::type;

    auto task = make_shared<packaged_task<return_type()>>(bind(forward<F>(f), forward<Args>(args)...));
    future<return_type> res = task->get_future();

    {
        lock_guard<mutex> lock(queue_mutex);
        if (stop) throw runtime_error("enqueue on stopped ThreadPool");
        tasks.emplace([task]() { (*task)(); });
    }

    condition.notify_one();
    return res;
}

// 析构函数:停止所有线程
ThreadPool::~ThreadPool() {
    {
        lock_guard<mutex> lock(queue_mutex);
        stop = true;
    }
    condition.notify_all();
    for (thread& worker : workers) {
        if (worker.joinable()) worker.join();
    }
}

4.2 使用线程池 

#include <iostream>
#include "ThreadPool.h" // 假设前面的代码在 ThreadPool.h 中
using namespace std;

int main() {
    // 创建一个包含 4 个线程的线程池
    ThreadPool pool(4);

    // 提交任务并获取结果
    auto result1 = pool.enqueue([](int a, int b) { return a + b; }, 2, 3);
    auto result2 = pool.enqueue([](int n) { return n * n; }, 5);

    cout << "Result1: " << result1.get() << endl;
    cout << "Result2: " << result2.get() << endl;

    return 0;
}

输出结果

Result1: 5
Result2: 25

结语

以上就是 C++ 11 多线程中线程池的基础知识点了。线程池是现代多线程编程的重要工具,线程池的原理:通过复用线程和任务队列,提高性能和资源利用率。std::async 的简单实现:快速实现异步任务处理。同时我们手动从零开始实现了一个功能完整的线程池。线程池可以大幅提升程序的效率,但在实际使用中,需要注意线程的同步和资源管理问题。

都看到这里了,点个赞再走呗朋友~

加油吧,预祝大家变得更强!

本文章已经生成可运行项目
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值