本文主要是介绍c++ 实现的简易线程池,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
//单例类
template<typename T>
class Singleton {
public:
static T &instance() {
call_once(onceFlag_, [&]{instance_ = new T(); });
return *instance_;
}
private:
Singleton()=default;
Singleton(const Singleton&) = delete;
Singleton &operator=(const Singleton&) = delete;
~Singleton() = default;
static once_flag onceFlag_;
static atomic<T *> instance_;
};
template<typename T>
atomic<T *> Singleton<T>::instance_ = nullptr;
template<typename T>
once_flag Singleton<T>::onceFlag_;
//阻塞队列
template<typename T>
class BlockingQueue {
public:
BlockingQueue() = default;
BlockingQueue(const BlockingQueue&) = delete;
BlockingQueue& operator=(const BlockingQueue&) = delete;
void push(const T& val) {
lock_guard<mutex> lock(mutex_);
data_.push(val);
cond_.notify_one();
}
T pop() {
unique_lock<mutex> lock(mutex_);
while (data_.empty()) {
cond_.wait(lock);
}
T tmp = data_.front();
data_.pop();
return tmp;
}
private:
queue<T> data_;
mutex mutex_;
condition_variable cond_;
};
//线程池
class TharedPool {
public:
using Functor = function<void()>;
TharedPool(): running_(true), taskQueue_(){
// num_of_computing_thread 是启动的线程数量,全局常量
for (int i = 0; i < num_of_computing_thread; ++i) {
threads_.push_back(thread(&workerThread,this));
}
}
void post(Functor functor) {
taskQueue_.push(functor);
}
//强制停止,不保证任务队列执行完毕。因为理论上线程池应该做成单例模式,与进程的生命周期相同,其实不用怎么考虑销毁,这边是特意先讨论下如何销毁才写上的
void stop() {
running_ = false;
//发送空任务,进行“唤醒”
for (int i = 0; i < threads_.size(); ++i) {
post([] {});
}
for (int i = 0; i < threads_.size(); ++i) {
threads_[i].join();
}
}
private:
static void workerThread(TharedPool* tp) {
while (tp->running_) {
Functor task = tp->taskQueue_.pop();
task();
}
}
BlockingQueue<Functor> taskQueue_;
vector<thread> threads_;
bool running_;
};
//配合上面的单例模式使用,或者写个单例模式类进行包装
这篇关于c++ 实现的简易线程池的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!