muduo之ThreadPool
生活随笔
收集整理的這篇文章主要介紹了
muduo之ThreadPool
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? ? ?muduo中的線程池。
ThreadPool.h
// Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: Shuo Chen (chenshuo at chenshuo dot com)#ifndef MUDUO_BASE_THREADPOOL_H #define MUDUO_BASE_THREADPOOL_H#include "muduo/base/Condition.h" #include "muduo/base/Mutex.h" #include "muduo/base/Thread.h" #include "muduo/base/Types.h"#include <deque> #include <vector>namespace muduo {class ThreadPool : noncopyable {public:typedef std::function<void ()> Task;explicit ThreadPool(const string& nameArg = string("ThreadPool"));~ThreadPool();// Must be called before start().void setMaxQueueSize(int maxSize) { maxQueueSize_ = maxSize; }//設置任務隊列的最大值void setThreadInitCallback(const Task& cb)//設置線程執行前的回調函數{ threadInitCallback_ = cb; }void start(int numThreads);void stop();const string& name() const{ return name_; }size_t queueSize() const;// Could block if maxQueueSize > 0// There is no move-only version of std::function in C++ as of C++14.// So we don't need to overload a const& and an && versions// as we do in (Bounded)BlockingQueue.// https://stackoverflow.com/a/25408989void run(Task f);private:bool isFull() const REQUIRES(mutex_);//判滿void runInThread();//線程池的線程運行函數Task take();//取任務函數mutable MutexLock mutex_;Condition notEmpty_ GUARDED_BY(mutex_);//不空conditionCondition notFull_ GUARDED_BY(mutex_); //未滿conditionstring name_;Task threadInitCallback_; //線程執行前的回調函數std::vector<std::unique_ptr<muduo::Thread>> threads_;//存放線程的隊列std::deque<Task> queue_ GUARDED_BY(mutex_);//存放任務的隊列,Task是function泛型size_t maxQueueSize_;//任務隊列大小bool running_; };} // namespace muduo#endif // MUDUO_BASE_THREADPOOL_HThreadPool.cc
// Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: Shuo Chen (chenshuo at chenshuo dot com)#include "muduo/base/ThreadPool.h"#include "muduo/base/Exception.h"#include <assert.h> #include <stdio.h> #include <iostream>using namespace muduo;ThreadPool::ThreadPool(const string& nameArg): mutex_(),notEmpty_(mutex_), //初始化的時候需要把condition和mutex關聯起來notFull_(mutex_),name_(nameArg),maxQueueSize_(0),//初始化0running_(false) { }ThreadPool::~ThreadPool() {if (running_)//如果線程池在運行,那就要進行內存處理,在stop()函數中執行{stop();} }void ThreadPool::start(int numThreads) {assert(threads_.empty());running_ = true;threads_.reserve(numThreads);//預留reserver個空間for (int i = 0; i < numThreads; ++i){char id[32];//id存儲線程idsnprintf(id, sizeof id, "%d", i+1);threads_.emplace_back(new muduo::Thread(std::bind(&ThreadPool::runInThread, this), name_+id));threads_[i]->start();//線程啟動}if (numThreads == 0 && threadInitCallback_){threadInitCallback_();} }void ThreadPool::stop() //釋放資源 {{MutexLockGuard lock(mutex_);running_ = false;notEmpty_.notifyAll();}for (auto& thr : threads_){thr->join();//資源回收} }size_t ThreadPool::queueSize() const //返回任務隊列的大小 {MutexLockGuard lock(mutex_);return queue_.size(); }void ThreadPool::run(Task task)//將任務添加到任務隊列 {printf("ThreadPool::run\n");if (threads_.empty()){task();}else{MutexLockGuard lock(mutex_);while (isFull())//判斷任務隊列是否滿{printf("notFull_.wait\n");notFull_.wait();}assert(!isFull());printf("2222\n");queue_.push_back(std::move(task));notEmpty_.notify();//此時任務隊列非空} }ThreadPool::Task ThreadPool::take()//取任務函數 {MutexLockGuard lock(mutex_);// always use a while-loop, due to spurious wakeupwhile (queue_.empty() && running_){notEmpty_.wait();}Task task;if (!queue_.empty()){task = queue_.front();queue_.pop_front(); if (maxQueueSize_ > 0) //取走任務后再判斷任務隊列的大小{notFull_.notify();}}return task; }bool ThreadPool::isFull() const {mutex_.assertLocked();std::cout << "maxQueueSize_" << maxQueueSize_ << "queue_.size()=" <<queue_.size() << std::endl;return maxQueueSize_ > 0 && queue_.size() >= maxQueueSize_; }void ThreadPool::runInThread()//線程池的線程運行函數 {try{if (threadInitCallback_){threadInitCallback_();}while (running_){Task task(take());if (task){task();}}}catch (const Exception& ex){fprintf(stderr, "exception caught in ThreadPool %s\n", name_.c_str());fprintf(stderr, "reason: %s\n", ex.what());fprintf(stderr, "stack trace: %s\n", ex.stackTrace());abort();}catch (const std::exception& ex){fprintf(stderr, "exception caught in ThreadPool %s\n", name_.c_str());fprintf(stderr, "reason: %s\n", ex.what());abort();}catch (...){fprintf(stderr, "unknown exception caught in ThreadPool %s\n", name_.c_str());throw; // rethrow} }?
總結
以上是生活随笔為你收集整理的muduo之ThreadPool的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: muduo之Thread
- 下一篇: muduo之CountDownLatch