线程池 | 改进版 1.改进点 1.如何能让用户提交任务的过程更加简单方便?
1 2 3 4 从 pool.submitTask (std::make_shared <MyTask>(1 , 100 )); 改为 pool.submitTask (sum1,10 ,20 );
省略掉用户自己创建myTask类和重写run方法的这个过程
直接传入函数作为线程函数,后面是该函数的参数作为任务给到线程池
使用可变参模板编程来实现
2.Result以及相关的类型都是自己写的,其实都是有现成的
使用future代替Result,future等价于咱们自己写的Result
2.改进后的 主要改动的就是submitTask函数,threadFunc少量改动,其他的函数没有改动
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 #ifndef THREADPOOL_H #define THREADPOOL_H #include <iostream> #include <vector> #include <queue> #include <memory> #include <atomic> #include <mutex> #include <condition_variable> #include <functional> #include <thread> #include <unordered_map> #include <future> const int TASK_MAX_THRESHHOLD = 2 ;const int THREAD_MAX_THRESHHOLD = 10 ;const int THREAD_MAX_TDLE_TIME = 10 ;enum class PoolMode { MODE_FIXED, MODE_CACHED, }; class Thread { public : using ThreadFunc = std::function<void (int )>; Thread (ThreadFunc func) :func_ (func), threadId_ (generateId_++) {} ~Thread () = default ; void start () { std::thread t (func_, threadId_) ; t.detach (); } int getId () const { return threadId_; } private : ThreadFunc func_; static int generateId_; int threadId_; }; int Thread::generateId_ = 0 ;class ThreadPool { public : ThreadPool () : initThreadSize_ (0 ), taskSize_ (0 ), idleThreadSize_ (0 ), threadSizeThresHold_ (THREAD_MAX_THRESHHOLD), taskQueMaxThresHold_ (TASK_MAX_THRESHHOLD), curThreadSize_ (0 ), poolMode_ (PoolMode::MODE_FIXED), isPoolRunning_ (false ) {} ~ThreadPool () { isPoolRunning_ = false ; std::unique_lock<std::mutex> lock (taskQueMtx_) ; notEmpty_.notify_all (); exitCoond_.wait (lock, [&]()->bool {return threads_.size () == 0 ; }); } void setMode (PoolMode mode) { if (checkRunningState ()) return ; poolMode_ = mode; } void setTaskQueMaxThresHold (int threshold) { taskQueMaxThresHold_ = threshold; } void setthreadSizeThresHold (int threshold) { if (checkRunningState ()) return ; if (poolMode_ == PoolMode::MODE_CACHED) { threadSizeThresHold_ = threshold; } } template <typename Func,typename ...Args> auto submitTask (Func&& func, Args&&... args) -> std::future<decltype (func(args...)) > { using RType = decltype (func (args...)); auto task = std::make_shared<std::packaged_task<RType ()>>( std::bind (std::forward<Func>(func), std::forward<Args>(args)...)); std::future<RType> result = task->get_future (); std::unique_lock<std::mutex> lock (taskQueMtx_) ; if (!notFull_.wait_for (lock, std::chrono::seconds (1 ), [&]()->bool {return taskQue_.size () < (size_t )taskQueMaxThresHold_; })) { std::cerr << "task queue is full,submit task fail" << std::endl; auto task = std::make_shared<std::packaged_task<RType ()>>( []()->RType {return RType (); } ); (*task)(); return task->get_future (); } taskQue_.emplace ([task]() {(*task)();}); taskSize_++; notEmpty_.notify_all (); if (poolMode_ == PoolMode::MODE_CACHED && taskSize_ > idleThreadSize_ && curThreadSize_ < threadSizeThresHold_) { std::cout << "create new thread........" << std::endl; auto ptr = std::make_unique <Thread>(std::bind (&ThreadPool::threadFunc, this , std::placeholders::_1)); int threadId = ptr->getId (); threads_.emplace (threadId, std::move (ptr)); threads_[threadId]->start (); curThreadSize_++; idleThreadSize_++; } return result; } void start (int initThreadSize = std::thread::hardware_concurrency()) { isPoolRunning_ = true ; initThreadSize_ = initThreadSize; curThreadSize_ = initThreadSize; for (int i = 0 ; i < initThreadSize_; i++) { auto ptr = std::make_unique <Thread>(std::bind (&ThreadPool::threadFunc, this , std::placeholders::_1)); int threadId = ptr->getId (); threads_.emplace (threadId, std::move (ptr)); } for (int i = 0 ; i < initThreadSize_; i++) { threads_[i]->start (); idleThreadSize_++; } } ThreadPool (const ThreadPool&) = delete ; ThreadPool& operator =(const ThreadPool&) = delete ; private : void threadFunc (int threadid) { auto lastTime = std::chrono::high_resolution_clock ().now (); for (;;) { Task task; { std::unique_lock<std::mutex> lock (taskQueMtx_) ; std::cout << "thread tid:" << std::this_thread::get_id () << "尝试获取任务" << std::endl; while (taskQue_.size () == 0 ) { if (!isPoolRunning_) { threads_.erase (threadid); std::cout << "threadid" << threadid << "已被回收" << std::endl; exitCoond_.notify_all (); return ; } if (poolMode_ == PoolMode::MODE_CACHED) { if (std::cv_status::timeout == notEmpty_.wait_for (lock, std::chrono::seconds (1 ))) { auto now = std::chrono::high_resolution_clock ().now (); auto dur = std::chrono::duration_cast <std::chrono::seconds> (now - lastTime); if (dur.count () >= THREAD_MAX_TDLE_TIME && curThreadSize_ > initThreadSize_) { threads_.erase (threadid); curThreadSize_--; idleThreadSize_--; std::cout << "threadid" << threadid << "已被回收" << std::endl; return ; } } } else { notEmpty_.wait (lock); } } idleThreadSize_--; std::cout << "thread tid:" << std::this_thread::get_id () << "获取任务成功" << std::endl; task = taskQue_.front (); taskQue_.pop (); taskSize_--; if (taskQue_.size () > 0 ) { notEmpty_.notify_all (); } notFull_.notify_all (); } if (task != nullptr ) { task (); } idleThreadSize_++; lastTime = std::chrono::high_resolution_clock ().now (); } } bool checkRunningState () const { return isPoolRunning_; } private : std::unordered_map<int , std::unique_ptr<Thread>> threads_; size_t initThreadSize_; std::atomic_int curThreadSize_; int threadSizeThresHold_; std::atomic_int idleThreadSize_; using Task = std::function<void ()>; std::queue<Task> taskQue_; std::atomic_int taskSize_; int taskQueMaxThresHold_; std::mutex taskQueMtx_; std::condition_variable notFull_; std::condition_variable notEmpty_; std::condition_variable exitCoond_; PoolMode poolMode_; std::atomic_bool isPoolRunning_; }; #endif
重难点:可变参模板编程,future和packaged_task的使用,bind和function的理解
packaged_task 、future知识点-CSDN博客
3.测试代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 #include "threadPool.h" #include <chrono> using namespace std;int sum (int a, int b) { this_thread::sleep_for (chrono::seconds (2 )); return a + b; } int main () { ThreadPool pool; pool.start (2 ); future<int > res= pool.submitTask (sum,10 ,20 ); future<int > res1 = pool.submitTask (sum, 10 , 20 ); future<int > res2 = pool.submitTask (sum, 10 , 20 ); future<int > res3 = pool.submitTask (sum, 10 , 20 ); future<int > res4 = pool.submitTask (sum, 10 , 20 ); cout << res.get () << endl; cout << res1. get () << endl; cout << res2. get () << endl; cout << res3. get () << endl; cout << res4. get () << endl; return 0 ; }