简单的线程池示例

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

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;
}
相关推荐
_dindong18 分钟前
牛客101:链表
数据结构·c++·笔记·学习·算法·链表
wuk99823 分钟前
基于位置式PID算法调节PWM占空比实现电机转速控制
单片机·嵌入式硬件·算法
不到满级不改名38 分钟前
EM算法 & 隐马尔可夫模型
算法
蓝创精英团队44 分钟前
C++DirectX9坐标系与基本图元之渲染状态(RenderState)_0304
前端·c++·性能优化
筏.k2 小时前
C++ 设计模式系列:生产者-消费者模式完全指南
开发语言·c++·设计模式
workflower5 小时前
单元测试-例子
java·开发语言·算法·django·个人开发·结对编程
LXS_3576 小时前
Day 05 C++ 入门 之 指针
开发语言·c++·笔记·学习方法·改行学it
MicroTech20257 小时前
微算法科技(MLGO)研发突破性低复杂度CFG算法,成功缓解边缘分裂学习中的掉队者问题
科技·学习·算法
墨染点香7 小时前
LeetCode 刷题【126. 单词接龙 II】
算法·leetcode·职场和发展
aloha_7898 小时前
力扣hot100做题整理91-100
数据结构·算法·leetcode