简单的线程池示例

线程池可以有效地管理和重用线程资源,避免频繁创建和销毁线程带来的开销。以下是一个简单的线程池示例。

cpp 复制代码
cpp
#include <iostream>
#include <vector>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>

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

    void enqueue(std::function<void()> func);

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;

    std::mutex queueMutex;
    std::condition_variable condition;
    bool stop;

    void worker();
};

ThreadPool::ThreadPool(size_t numThreads) : stop(false) {
    for (size_t i = 0; i < numThreads; ++i) {
        workers.emplace_back([this] { this->worker(); });
    }
}

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

void ThreadPool::enqueue(std::function<void()> func) {
    {
        std::unique_lock<std::mutex> lock(queueMutex);
        tasks.push(func);
    }
    condition.notify_one();
}

void ThreadPool::worker() {
    while (true) {
        std::function<void()> task;
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
            if (this->stop && this->tasks.empty()) return;
            task = std::move(this->tasks.front());
            this->tasks.pop();
        }
        task();
    }
}

// 示例使用
void exampleTask(int n) {
    std::cout << "Task " << n << " is being processed by thread " << std::this_thread::get_id() << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main() {
    ThreadPool pool(4); // 创建具有4个线程的线程池

    for (int i = 0; i < 10; ++i) {
        pool.enqueue([i] { exampleTask(i); });
    }`在这里插入代码片`

    std::this_thread::sleep_for(std::chrono::seconds(5)); // 保证主线程等待足够长的时间让线程池处理完任务
    return 0;
}
相关推荐
不可求~24 分钟前
C++ std::string_view 不是字符串:从悬空引用到安全用法
java·开发语言·c++
小小龙学IT1 小时前
C++ 正则表达式完全指南:从 std::regex 实战到 RE2 引擎原理(NFA/DFA/回溯陷阱)
c++·正则表达式
蛋先生DX1 小时前
你瘦不下来但大模型可以:量化原理了解一下
深度学习·算法·llm
(╹◡╹)3 小时前
18.剪枝
算法·机器学习·剪枝
Fa_Mian_Tuan4 小时前
图论基础|邻接矩阵超详细讲解(含无向/有向/带权图+完整可运行C语言代码)
c语言·数据结构·笔记·算法·图论
hanhahai4 小时前
指针与函数(函数指针与指针函数)
算法
码匠许师傅4 小时前
【C++ 面试真题】聊聊 C++ 的序列容器
java·c++·面试
ValhallaCoder4 小时前
Leetcode-hot100(2026.08.17)
python·算法·leetcode
C++ 老炮儿的技术栈5 小时前
Qt5.9.1 Windows 完整开发环境搭建流程
开发语言·c++·windows·qt·编辑器·代码化
泡沫冰@5 小时前
GO 语言基础
开发语言·算法·golang