«

如何在C++中实现线程池_线程池设计与实现详解

磁力搜索 • 4 天前 • 3 次点击 • 资讯分享


线程池是通过预先创建并维护一组线程来提高任务执行效率的机制。1. 核心组件包括任务队列、工作线程和线程池管理器,其中任务队列用于存储待执行任务,工作线程负责执行任务,管理器负责线程池的生命周期和任务调度。2. 线程池大小应根据任务类型和系统资源合理设置:cpu密集型任务建议设为cpu核心数+1,i/o密集型任务可依据公式“线程数 = cpu核心数 × (1 + i/o等待时间 / cpu计算时间)”设定。3. 异常处理可通过在工作线程中捕获异常并记录日志实现,防止程序崩溃。4. 优雅关闭线程池需通知线程停止接收新任务并在完成当前任务后退出,析构函数中设置stop标志并唤醒所有线程以确保其退出循环,但如需确保所有任务执行完毕,还需额外机制支持。

如何在C++中实现线程池_线程池设计与实现详解

线程池,简单来说,就是预先创建好一批线程,让它们在那里“待命”,而不是每次需要执行任务的时候才临时创建。这样做的好处显而易见:避免了频繁创建和销毁线程的开销,提高了程序的响应速度和效率。

如何在C++中实现线程池_线程池设计与实现详解

解决方案

如何在C++中实现线程池_线程池设计与实现详解

要在C++中实现线程池,我们需要考虑以下几个核心组件:

立即学习“C++免费学习笔记(深入)”;

如何在C++中实现线程池_线程池设计与实现详解
  1. 任务队列 (Task Queue): 用于存放待执行的任务。通常使用线程安全的队列,例如std::queue配合std::mutex和std::condition_variable。
  2. 工作线程 (Worker Threads): 负责从任务队列中取出任务并执行。这些线程在线程池创建时启动,并在线程池销毁时停止。
  3. 线程池管理器 (Thread Pool Manager): 负责线程池的创建、销毁、任务提交等管理工作。

下面是一个简单的C++线程池实现示例:

#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>

class ThreadPool {
public:
    ThreadPool(size_t numThreads) : stop(false) {
        threads.resize(numThreads);
        for (size_t i = 0; i < numThreads; ++i) {
            threads[i] = std::thread([this]() {
                while (true) {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(queueMutex);
                        condition.wait(lock, [this]() { return stop || !tasks.empty(); });
                        if (stop && tasks.empty()) {
                            return;
                        }
                        task = tasks.front();
                        tasks.pop();
                    }
                    task();
                }
            });
        }
    }

    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)...);
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            tasks.push(task);
        }
        condition.notify_one();
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            stop = true;
        }
        condition.notify_all();
        for (std::thread& thread : threads) {
            thread.join();
        }
    }

private:
    std::vector<std::thread> threads;
    std::queue<std::function<void()>> tasks;
    std::mutex queueMutex;
    std::condition_variable condition;
    bool stop;
};

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

    for (int i = 0; i < 8; ++i) {
        pool.enqueue([i]() {
            std::cout << "Task " << i << " executed by thread " << std::this_thread::get_id() << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟耗时操作
        });
    }

    std::this_thread::sleep_for(std::chrono::seconds(1)); // 等待任务完成

    return 0;
}
登录后复制


    还没收到回复