学习记录
- 《现代C++语言核心特性解析》
- 第11章 非受限联合类型
- 第12章 委托构造函数
- 第13章 继承构造函数
- 第14章 强枚举类型
- 第15章 扩展的聚合类型
- 第16章 override和final说明符
- 第17章 基于范围的for循化
- 第18章 支持初始化语句的if和switch
- 第19章 static_assert声明
- 第20章 结构化绑定
- 第21章 noexcept关键字
- 第22章 类型别名和别名模板
- 第23章 指针字面值nullptr
- 第24章 三向比较
线程池实现
/*
* @Author : mark
* @Date : 2020-06-15
* @copyleft Apache 2.0
*/
#include <thread>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <queue>
#include <functional>
#include <cassert>
class ThreadPool{
public:
explicit ThreadPool(const size_t poolSize):pool_(std::make_shared<Pool>()){
assert(poolSize > 0);
for(size_t i = 0; i < poolSize; i++){
std::thread([pool = pool_]{
std::unique_lock<std::mutex> lock(pool->m_);
while(true){
if(!pool->tasks.empty()){
auto task = std::move(pool->tasks.front());
pool->tasks.pop();
lock.unlock();
task();
lock.lock();
}else if(pool->isClosed){
break;
}else{
pool->cond_.wait(lock);
}
}
}).detach();
}
}
ThreadPool() = default;
ThreadPool(ThreadPool&&) = default;
~ThreadPool(){
if(static_cast<bool>(pool_)){
{
std::lock_guard<std::mutex> lock(pool_->m_);
pool_->isClosed = true;
}
pool_->cond_.notify_all();
}
}
template<class F>
void AddTask(F&& task){
{
std::lock_guard<std::mutex> lock(pool_->m_);
pool_->tasks.emplace(std::forward<F>(task));
}
pool_->cond_.notify_one();
}
private:
struct Pool{
std::mutex m_;
std::condition_variable cond_;
bool isClosed;
std::queue<std::function<void()>> tasks;
};
std::shared_ptr<Pool> pool_;
};
单例模式实现
class Widget{
public:
static Widget* Instance(){
static Widget ptr;
return &ptr;
}
int a = 0;
private:
Widget(){};
~Widget(){};
};
梧桐树(嘿嘿)
#我的秋招日记#