threadpool.h
#ifndef THREADPOOL_H
#define THREADPOOL_H
#include <vector>
#include <queue>
#include <memory>
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <unordered_map>
class Any
{
public:
Any() = default;
~Any() = default;
Any(const Any&) = delete;
Any& operator=(const Any&) = delete;
Any(Any&&) = default;
Any& operator=(Any&&) = default;
template<typename T>
Any(T data) : base_(std::make_unique<Derive<T>>(data))
{}
template<typename T>
T cast_()
{
Derive<T>* pd = dynamic_cast<Derive<T>*>(base_.get());
if (pd == nullptr)
{
throw "type is unmatch!";
}
return pd->data_;
}
private:
class Base
{
public:
virtual ~Base() = default;
};
template<typename T>
class Derive : public Base
{
public:
Derive(T data) : data_(data)
{}
T data_;
};
private:
std::unique_ptr<Base> base_;
};
class Semaphore
{
public:
Semaphore(int limit = 0)
:resLimit_(limit)
{}
~Semaphore() = default;
void wait()
{
std::unique_lock<std::mutex> lock(mtx_);
cond_.wait(lock, [&]()->bool {return resLimit_ > 0; });
resLimit_--;
}
void post()
{
std::unique_lock<std::mutex> lock(mtx_);
resLimit_++;
cond_.notify_all();
}
private:
int resLimit_;
std::mutex mtx_;
std::condition_variable cond_;
};
class Task;
class Result
{
public:
Result(std::shared_ptr<Task> task, bool isValid = true);
~Result() = default;
void setVal(Any any);
Any get();
private:
Any any_;
Semaphore sem_;
std::shared_ptr<Task> task_;
std::atomic_bool isValid_;
};
class Task
{
public:
Task();
~Task() = default;
void exec();
void setResult(Result* res);
virtual Any run() = 0;
private:
Result* result_;
};
enum class PoolMode
{
MODE_FIXED,
MODE_CACHED,
};
class Thread
{
public:
using ThreadFunc = std::function<void(int)>;
Thread(ThreadFunc func);
~Thread();
void start();
int getId()const;
private:
ThreadFunc func_;
static int generateId_;
int threadId_;
};
class ThreadPool
{
public:
ThreadPool();
~ThreadPool();
void setMode(PoolMode mode);
void setTaskQueMaxThreshHold(int threshhold);
void setThreadSizeThreshHold(int threshhold);
Result submitTask(std::shared_ptr<Task> sp);
void start(int initThreadSize = std::thread::hardware_concurrency());
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
private:
void threadFunc(int threadid);
bool checkRunningState() const;
private:
std::unordered_map<int, std::unique_ptr<Thread>> threads_;
int initThreadSize_;
int threadSizeThreshHold_;
std::atomic_int curThreadSize_;
std::atomic_int idleThreadSize_;
std::queue<std::shared_ptr<Task>> taskQue_;
std::atomic_int taskSize_;
int taskQueMaxThreshHold_;
std::mutex taskQueMtx_;
std::condition_variable notFull_;
std::condition_variable notEmpty_;
std::condition_variable exitCond_;
PoolMode poolMode_;
std::atomic_bool isPoolRunning_;
};
threadpool.cc
#include "threadpool.h"
#include <functional>
#include <thread>
#include <iostream>
const int TASK_MAX_THRESHHOLD = INT32_MAX;
const int THREAD_MAX_THRESHHOLD = 1024;
const int THREAD_MAX_IDLE_TIME = 60;
ThreadPool::ThreadPool()
: initThreadSize_(0)
, taskSize_(0)
, idleThreadSize_(0)
, curThreadSize_(0)
, taskQueMaxThreshHold_(TASK_MAX_THRESHHOLD)
, threadSizeThreshHold_(THREAD_MAX_THRESHHOLD)
, poolMode_(PoolMode::MODE_FIXED)
, isPoolRunning_(false)
{}
ThreadPool::~ThreadPool()
{
isPoolRunning_ = false;
std::unique_lock<std::mutex> lock(taskQueMtx_);
notEmpty_.notify_all();
exitCond_.wait(lock, [&]()->bool {return threads_.size() == 0; });
}
void ThreadPool::setMode(PoolMode mode)
{
if (checkRunningState())
return;
poolMode_ = mode;
}
void ThreadPool::setTaskQueMaxThreshHold(int threshhold)
{
if (checkRunningState())
return;
taskQueMaxThreshHold_ = threshhold;
}
void ThreadPool::setThreadSizeThreshHold(int threshhold)
{
if (checkRunningState())
return;
if (poolMode_ == PoolMode::MODE_CACHED)
{
threadSizeThreshHold_ = threshhold;
}
}
Result ThreadPool::submitTask(std::shared_ptr<Task> sp)
{
std::unique_lock<std::mutex> lock(taskQueMtx_);
if (!notFull_.wait_for(lock, std::chrono::seconds(1),
[&]()->bool { return taskQue_.size() < (size_t)taskQueMaxThreshHold_; }))
{
std::cerr << "task queue is full, submit task fail." << std::endl;
return Result(sp, false);
}
taskQue_.emplace(sp);
taskSize_++;
notEmpty_.notify_all();
if (poolMode_ == PoolMode::MODE_CACHED
&& taskSize_ > idleThreadSize_
&& curThreadSize_ < threadSizeThreshHold_)
{
std::cout << ">>> create new thread..." << std::endl;
auto ptr = std::make_unique<Thread>(std::bind(&ThreadPool::threadFunc, this, std::placeholders::_1));
int threadId = ptr->getId();
threads_.emplace(threadId, std::move(ptr));
threads_[threadId]->start();
curThreadSize_++;
idleThreadSize_++;
}
return Result(sp);
}
void ThreadPool::start(int initThreadSize)
{
isPoolRunning_ = true;
initThreadSize_ = initThreadSize;
curThreadSize_ = initThreadSize;
for (int i = 0; i < initThreadSize_; i++)
{
auto ptr = std::make_unique<Thread>(std::bind(&ThreadPool::threadFunc, this, std::placeholders::_1));
int threadId = ptr->getId();
threads_.emplace(threadId, std::move(ptr));
}
for (int i = 0; i < initThreadSize_; i++)
{
threads_[i]->start();
idleThreadSize_++;
}
}
void ThreadPool::threadFunc(int threadid)
{
auto lastTime = std::chrono::high_resolution_clock().now();
for (;;)
{
std::shared_ptr<Task> task;
{
std::unique_lock<std::mutex> lock(taskQueMtx_);
std::cout << "tid:" << std::this_thread::get_id()
<< "尝试获取任务..." << std::endl;
while (taskQue_.size() == 0)
{
if (!isPoolRunning_)
{
threads_.erase(threadid);
std::cout << "threadid:" << std::this_thread::get_id() << " exit!"
<< std::endl;
exitCond_.notify_all();
return;
}
if (poolMode_ == PoolMode::MODE_CACHED)
{
if (std::cv_status::timeout ==
notEmpty_.wait_for(lock, std::chrono::seconds(1)))
{
auto now = std::chrono::high_resolution_clock().now();
auto dur = std::chrono::duration_cast<std::chrono::seconds>(now - lastTime);
if (dur.count() >= THREAD_MAX_IDLE_TIME
&& curThreadSize_ > initThreadSize_)
{
threads_.erase(threadid);
curThreadSize_--;
idleThreadSize_--;
std::cout << "threadid:" << std::this_thread::get_id() << " exit!"
<< std::endl;
return;
}
}
}
else
{
notEmpty_.wait(lock);
}
}
idleThreadSize_--;
std::cout << "tid:" << std::this_thread::get_id()
<< "获取任务成功..." << std::endl;
task = taskQue_.front();
taskQue_.pop();
taskSize_--;
if (taskQue_.size() > 0)
{
notEmpty_.notify_all();
}
notFull_.notify_all();
}
if (task != nullptr)
{
task->exec();
}
idleThreadSize_++;
lastTime = std::chrono::high_resolution_clock().now();
}
}
bool ThreadPool::checkRunningState() const
{
return isPoolRunning_;
}
int Thread::generateId_ = 0;
Thread::Thread(ThreadFunc func)
: func_(func)
, threadId_(generateId_++)
{}
Thread::~Thread() {}
void Thread::start()
{
std::thread t(func_, threadId_);
t.detach();
}
int Thread::getId()const
{
return threadId_;
}
Task::Task()
: result_(nullptr)
{}
void Task::exec()
{
if (result_ != nullptr)
{
result_->setVal(run());
}
}
void Task::setResult(Result* res)
{
result_ = res;
}
Result::Result(std::shared_ptr<Task> task, bool isValid)
: isValid_(isValid)
, task_(task)
{
task_->setResult(this);
}
Any Result::get()
{
if (!isValid_)
{
return "";
}
sem_.wait();
return std::move(any_);
}
void Result::setVal(Any any)
{
this->any_ = std::move(any);
sem_.post();
}
示例
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
#include "threadpool.h"
using uLong = unsigned long long;
class MyTask : public Task
{
public:
MyTask(int begin, int end)
: begin_(begin)
, end_(end)
{}
Any run()
{
std::cout << "tid:" << std::this_thread::get_id()
<< "begin!" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
uLong sum = 0;
for (uLong i = begin_; i <= end_; i++)
sum += i;
std::cout << "tid:" << std::this_thread::get_id()
<< "end!" << std::endl;
return sum;
}
private:
int begin_;
int end_;
};
int main()
{
{
ThreadPool pool;
pool.setMode(PoolMode::MODE_CACHED);
pool.start(2);
Result res1 = pool.submitTask(std::make_shared<MyTask>(1, 100000000));
Result res2 = pool.submitTask(std::make_shared<MyTask>(100000001, 200000000));
pool.submitTask(std::make_shared<MyTask>(100000001, 200000000));
pool.submitTask(std::make_shared<MyTask>(100000001, 200000000));
pool.submitTask(std::make_shared<MyTask>(100000001, 200000000));
}
cout << "main over!" << endl;
getchar();
#if 0
{
ThreadPool pool;
pool.setMode(PoolMode::MODE_CACHED);
pool.start(4);
Result res1 = pool.submitTask(std::make_shared<MyTask>(1, 100000000));
Result res2 = pool.submitTask(std::make_shared<MyTask>(100000001, 200000000));
Result res3 = pool.submitTask(std::make_shared<MyTask>(200000001, 300000000));
pool.submitTask(std::make_shared<MyTask>(200000001, 300000000));
pool.submitTask(std::make_shared<MyTask>(200000001, 300000000));
pool.submitTask(std::make_shared<MyTask>(200000001, 300000000));
uLong sum1 = res1.get().cast_<uLong>();
uLong sum2 = res2.get().cast_<uLong>();
uLong sum3 = res3.get().cast_<uLong>();
cout << (sum1 + sum2 + sum3) << endl;
}
getchar();
#endif
}