C++线程池的实现

8 篇文章 0 订阅
8 篇文章 0 订阅
#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

东哥爱编程

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

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

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

打赏作者

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

抵扣说明:

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

余额充值