c++11 线程池


也可参考:  https://www.cnblogs.com/ailumiyana/p/10016965.html  *** https://blog.csdn.net/jlusuoya/article/details/74505558  ***  https://www.cnblogs.com/magicsoar/p/3788180.html  *****   //nocopyable类,不可拷贝基类继承它,派生类不可拷贝 //nocopyable.h
#ifndef NOCOPYABLE_H #define NOCOPYABLE_H   namespace fivestar {   class nocopyable   {   private:       nocopyable(const nocopyable& x) = delete;       nocopyable& operator=(const nocopyable&x) = delete;   public:       nocopyable() = default;       ~nocopyable() = default;   };   }   #endif // NOCOPYABLE_H   //ThreadPool.h #ifndef THREADPOOL_H #define THREADPOOL_H   #include #include #include #include #include #include #include #include   #include "nocopyable.h" namespace fivestar {   class ThreadPool:public nocopyable   {   public:       typedef std::function Task;         explicit ThreadPool(const std::string &name = std::string());       ~ThreadPool();           void start(int numThreads);//设置线程数,创建numThreads个线程       void stop();//线程池结束       void run(const Task& f);//任务f在线程池中运行       void setMaxQueueSize(int maxSize) { _maxQueueSize = maxSize; }//设置任务队列可存放最大任务数   private:       bool isFull();//任务队列是否已满       void runInThread();//线程池中每个thread执行的function       Task take();//从任务队列中取出一个任务         std::mutex _mutex;       std::condition_variable _notEmpty;       std::condition_variable _notFull;       std::string _name;       std::vector _threads;       std::deque _queue;       size_t _maxQueueSize;       bool _running;   }; }   #endif // THREADPOOL_H    

注意:

1 .为线程池添加任务之前一定要调用setMaxQueueSize,设置任务队列可存放的最大任务数,否则线程池退化为单线程

2 若不调用start创建线程,则线程池退化为单线程

测试代码

#include #include "ThreadPool.h"   using namespace std;   void Test(int i) {     printf("I love you %d time\n",i); }   int main() {     fivestar::ThreadPool threadPool;     threadPool.setMaxQueueSize(10);     threadPool.start(2);       for(int i = 0;i < 10;++i)     {         auto task = bind(Test,i);         threadPool.run(task);     }       getchar();     return 0; }