C++线程池的实现

文章展示了一个使用C++实现的线程池类ThreadPool,它创建指定数量的工作线程来执行任务。线程池接受任务并使用互斥锁和条件变量进行同步,确保在停止时正确处理未完成的任务。在主函数中,创建了一个线程池实例,并向其添加了多个SayHello任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

#define NUM_THREADS 5

class ThreadPool {
public:
    explicit ThreadPool(size_t size):stop_(false) {
        // 创建线程池
        for(size_t i = 0; i < size; i++) {
            threads_.emplace_back([this] {
                while (true) {
                    unique_lock<mutex> lock(mutex_);
                    printf("wait");
                    condition_.wait(lock, [this] {return stop_ || !tasks_.empty();});
                    if(stop_ && tasks_.empty() ) {
                        return;
                    }
                    auto task = move(tasks_.front());
                    tasks_.pop();
                    lock.unlock();
                    task();
                }
            });
        }
    }
    template<class F>
    void addTask(F&& f) {
        printf("add");
        std::unique_lock<mutex> lock(mutex_);
        tasks_.emplace(forward<F>(f));
        condition_.notify_one();
    }
    ~ThreadPool() {
        printf("pool delete");
        std::unique_lock<std::mutex> lock(mutex_);
        stop_ = true;
        condition_.notify_all();
        for (auto& thread : threads_) {
            thread.join();
        }
    }
private:
    bool stop_;
    std::vector<std::thread> threads_;
    std::queue<std::function<void()>> tasks_;
    std::mutex mutex_;
    condition_variable condition_;
};
// 线程的运行函数
void say_hello(int num)
{
    printf("Hello Runoob!%d\n", num);
}
 

 
void SayHello(int num) {
    // std::cout << "Hello from thread " << num << std::endl;
    for(int i = 0; i < num; i ++) {
        cout << "循环" << num << endl;
    }
}
 
int main() {
    ThreadPool pool(16);
    for (int i = 0; i < 800; ++i) {
        pool.addTask([i] { SayHello(i); });
    }
    std::this_thread::sleep_for(std::chrono::seconds(5));
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东哥aigc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值