简单的线程池示例

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

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;
}
相关推荐
BIT_Legend27 分钟前
Torch 模型 model => .onnx => .trt 及利用 TensorTR 在 C++ 下的模型部署教程
c++·人工智能·python·深度学习
加减法原则29 分钟前
求最大子数组和 | LeetCode刷题
算法
折枝寄北1 小时前
从零开始 | C语言基础刷题DAY1
c语言·开发语言·算法
.ccl1 小时前
蓝桥杯省赛真题C++B组2024-握手问题
c++·算法·蓝桥杯
arong_xu1 小时前
C++20 新特性总结
算法·c++20
hrrrrb2 小时前
【C语言】指针篇
c语言·数据结构·算法
神里流~霜灭2 小时前
下降路径最⼩和(medium)
数据结构·c++·算法·链表·贪心算法·动态规划
tan180°2 小时前
版本控制器Git(1)
c++·git·后端
编程绿豆侠2 小时前
力扣HOT100之双指针:11. 盛最多水的容器
算法·leetcode·职场和发展
JANGHIGH2 小时前
c++ constraints与concepts使用笔记
c++·笔记