[C++11] ThreadPool

背景

近期,在造一个异步HTTP调用的轮子;https://github.com/Sai-Jiang

简单来说,通过一个Restful接口,代理会接收异步HTTP调用的请求;

这些接收到的异步HTTP调用请求,将会由代理代为去执行;

适用的场景,主要是低时延接口调用高时延接口;

HTTP的调用,目前准备用线程池来做;

线程池实现中的任务队列,我就直接复用了之前博客中的BoundedBlockingQueue;

ps. 有时候,写C++有种跟“说话总是说一半“的人聊天的感觉;

To the point

#pragma once

#include <mutex>
#include <condition_variable>
#include <queue>
#include <thread>
#include "BoundedBlockingQueue.hpp"

class ThreadPool {
public:
    using Task = std::function<void()>;

    ThreadPool(int maxTasks, int maxThreads) :
                IsRunning(false),
                maxThreads(maxThreads),
                queue_(maxTasks) {
    }

    ThreadPool(const ThreadPool&) = delete;
    ThreadPool &operator=(const ThreadPool&) = delete;

    ~ThreadPool() {
        if (IsRunning) Stop();
    }

    bool Start();
    bool Stop();

    void PutTask(const Task &task) {
        queue_.put(task);
    }

private:
    void RunInLoop();

private:
    std::atomic<bool> IsRunning;
    int maxThreads;
    std::vector<std::thread> threads_;
    BoundedBlockingQueue<Task> queue_;
};

void ThreadPool::RunInLoop() {
    while (IsRunning) {
        Task todo = queue_.take();
        if (todo) todo();
    }
}

bool ThreadPool::Start() {
    IsRunning = true;
    for (int i = 0; i < maxThreads; i++)
        threads_.emplace_back(std::thread(std::bind(&ThreadPool::RunInLoop, this)));
    return true;
}

bool ThreadPool::Stop() {
    IsRunning = false;
    for (auto &thread : threads_) {
        queue_.put(Task());
        thread.join();
    }
    return true;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值