一个简洁版的线程池 去除了minthreadnum,maxthreadnum进一步控制线程数目的功能 只是实现维持一定数量线程,在有任务时唤醒去执行的简单逻辑。
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <condition_variable>
#include <cassert>
#include <windows.h>
using namespace std;
int num=0;
class ThreadPool{
public:
explicit ThreadPool(size_t threadCount=8):pool_(std::make_shared<Pool>()){
assert(threadCount>0);
for (size_t i = 0; i < threadCount; i++)
{
std::
thread([pool = pool_]
{
std::unique_lock<std::mutex> locker(pool->mtx);
while(true){
if(!pool->Q.empty()){
auto task=std::move(pool->Q.front());
pool->Q.pop();
locker.unlock();
task();
locker.lock();
}else if(pool->isClosed) break;
else pool->cond.wait(locker);
} })
.detach();
}
}
ThreadPool()=default;
ThreadPool(ThreadPool &&)=default;
~ThreadPool(){
if(static_cast<bool>(pool_)){
{
std::lock_guard<std::mutex> locker(pool_->mtx);
pool_->isClosed=true;
}
pool_->cond.notify_all();
}
}
template <typename F>
void AddTask(F &&task){
{
std::lock_guard<std::mutex> locker(pool_->mtx);
pool_->Q.emplace(std::forward<F>(task));
}
pool_->cond.notify_one();
}
private:
typedef struct Pool{
std::mutex mtx;
std::condition_variable cond;
bool isClosed;
std::queue<std::function<void()>> Q;
Pool(){}
}Pool;
std::shared_ptr<Pool> pool_;
};
void taskFunc(void* arg){
int num=*(int*)arg;
cout<<"thread is working,number="<<num<<endl;
}
int main(){
ThreadPool pool(8);
for(int i=0;i<100;i++)
pool.AddTask(std::bind(&taskFunc,&num));
pthread_exit(NULL);
return 0;
}
|