背景
近期,在造一个异步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;
}