当前位置:   article > 正文

c++11线程池的实现原理及回调函数的使用_c++ 回调函数 多线程

c++ 回调函数 多线程

关于线程池

简单来说就是有一堆已经创建好的线程(最大数目一定),初始时他们都处于空闲状态。当有新的任务进来,从线程池中取出一个空闲的线程处理任务然后当任务处理完成之后,该线程被重新放回到线程池中,供其他的任务使用。当线程池中的线程都在处理任务时,就没有空闲线程供使用,此时,若有新的任务产生,只能等待线程池中有线程结束任务空闲才能执行。

线程池优点

线程本来就是可重用的资源,不需要每次使用时都进行初始化。因此可以采用有限的线程个数处理无限的任务。既可以提高速度和效率,又降低线程频繁创建的开销。比如要异步干的活,就没必要等待。丢到线程池里处理,结果在回调中处理。频繁执行的异步任务,若每次都创建线程势必造成不小的开销。像java中频繁执行的异步任务,就new Therad{}.start(),然后就不管了不是个好的办法,频繁调用可能会触发GC,带来严重的性能问题,类似这种就该使用线程池。

还比如把计算任务都放在主线程进行,那么势必会阻塞主线程的处理流程,无法做到实时处理。使用多线程技术是大家自然而然想到的方案。在上述的场景中必然会频繁的创建和销毁线程,这样的开销相信是不能接受的,此时线程池技术便是很好的选择。
另外在一些高并发的网络应用中,线程池也是常用的技术。陈硕大神推荐的C++多线程服务端编程模式为:one loop per thread + thread pool,通常会有单独的线程负责接受来自客户端的请求,对请求稍作解析后将数据处理的任务提交到专门的计算线程池。

实现原理及思路

大致原理是创建一个类,管理一个任务队列,一个线程队列。然后每次取一个任务分配给一个线程去做,循环往复。任务队列负责存放主线程需要处理的任务,工作线程队列其实是一个死循环,负责从任务队列中取出和运行任务,可以看成是一个生产者和多个消费者的模型。

c++11虽然加入了线程库thread,然而 c++ 对于多线程的支持还是比较低级,稍微高级一点的用法都需要自己去实现,还有备受期待的网络库,至今标准库里还没有支持,常用asio替代。感谢网上大神的奉献,这里贴上源码并完善下使用方法,主要是增加了使用示例及回调函数的使用。

使用举例

  1. #include <iostream>
  2. #include <chrono>
  3. #include <thread>
  4. #include <future>
  5. #include "threadpool.h"
  6. using namespace std;
  7. using namespace std::chrono;
  8. //仿函数示例
  9. struct gfun {
  10. int operator()(int n) {
  11. printf("%d hello, gfun ! %d\n" ,n, std::this_thread::get_id() );
  12. return 42;
  13. }
  14. };
  15. class A {
  16. public:
  17. static std::string Bfun(int n, std::string str, char c) {
  18. std::cout << n << " hello, Bfun ! "<< str.c_str() <<" " << (int)c <<" " << std::this_thread::get_id() << std::endl;
  19. return str;
  20. }
  21. };
  22. int main() {
  23. cout << "hello,this is a test using threadpool" <<endl;
  24. me::ThreadPool pool(4);
  25. std::vector< std::future<int> > results;
  26. //lambada表达式 匿名函数线程中执行
  27. pool.commit([] {
  28. std::cout << "this is running in pool therad " << std::endl;
  29. std::this_thread::sleep_for(std::chrono::seconds(1));
  30. });
  31. //仿函数放到线程池中执行
  32. std::future<int> fg = pool.commit(gfun{},0);
  33. std::future<std::string> gh = pool.commit(A::Bfun, 999,"mult args", 123);
  34. //回调函数示例,模拟耗时操作,结果回调输出
  35. auto fetchDataFromDB = [](std::string recvdData,std::function<int(std::string &)> cback) {
  36. // Make sure that function takes 5 seconds to complete
  37. std::this_thread::sleep_for(seconds(5));
  38. //Do stuff like creating DB Connection and fetching Data
  39. if(cback != nullptr){
  40. std::string out = "this is from callback ";
  41. cback(out);
  42. }
  43. return "DB_" + recvdData;
  44. };
  45. //模拟,回调
  46. fetchDataFromDB("aaa",[&](std::string &result){
  47. std::cout << "callback result:" << result << std::endl;
  48. return 0;
  49. } );
  50. //把fetchDataFromDB这一IO耗时任务放到线程里异步执行
  51. //
  52. std::future<std::string> resultFromDB = std::async(std::launch::async, fetchDataFromDB, "Data0",
  53. [&](std::string &result){
  54. std::cout << "callback result from thread:" << result << std::endl;
  55. return 0;
  56. });
  57. //把fetchDataFromDB这一IO耗时操作放到pool中的效果
  58. pool.commit(fetchDataFromDB,"Data1",[&](std::string &result){
  59. std::cout << "callback result from pool thread:" << result << std::endl;
  60. return 0;
  61. });
  62. for(int i = 0; i < 8; ++i) {
  63. results.emplace_back(
  64. pool.commit([i] {
  65. std::cout << "hello " << i << std::endl;
  66. std::this_thread::sleep_for(std::chrono::seconds(1));
  67. std::cout << "world " << i << std::endl;
  68. return i*i;
  69. })
  70. );
  71. }
  72. for(auto && result: results){
  73. std::cout << result.get() << ' ';
  74. }
  75. std::cout << std::endl;
  76. }

以下是具体实现过程: 

  1. #pragma once
  2. #ifndef THREAD_POOL_H
  3. #define THREAD_POOL_H
  4. #include <vector>
  5. #include <queue>
  6. #include <atomic>
  7. #include <future>
  8. //#include <condition_variable>
  9. //#include <thread>
  10. #include <functional>
  11. #include <stdexcept>
  12. namespace me
  13. {
  14. using namespace std;
  15. //线程池最大容量,应尽量设小一点
  16. #define THREADPOOL_MAX_NUM 16
  17. //#define THREADPOOL_AUTO_GROW
  18. //线程池,可以提交变参函数或拉姆达表达式的匿名函数执行,可以获取执行返回值
  19. //不直接支持类成员函数, 支持类静态成员函数或全局函数,Opteron()函数等
  20. class ThreadPool
  21. {
  22. using Task = function<void()>; //定义类型
  23. vector<thread> _pool; //线程池
  24. queue<Task> _tasks; //任务队列
  25. mutex _lock; //同步
  26. condition_variable _task_cv; //条件阻塞
  27. atomic<bool> _run{ true }; //线程池是否执行
  28. atomic<int> _idlThrNum{ 0 }; //空闲线程数量
  29. public:
  30. inline ThreadPool(unsigned short size = 4) { addThread(size); }
  31. inline ~ThreadPool()
  32. {
  33. _run=false;
  34. _task_cv.notify_all(); // 唤醒所有线程执行
  35. for (thread& thread : _pool) {
  36. //thread.detach(); // 让线程“自生自灭”
  37. if(thread.joinable())
  38. thread.join(); // 等待任务结束, 前提:线程一定会执行完
  39. }
  40. }
  41. public:
  42. // 提交一个任务
  43. // 调用.get()获取返回值会等待任务执行完,获取返回值
  44. // 有两种方法可以实现调用类成员,
  45. // 一种是使用 bind: .commit(std::bind(&Dog::sayHello, &dog));
  46. // 一种是用 mem_fn: .commit(std::mem_fn(&Dog::sayHello), this)
  47. template<class F, class... Args>
  48. auto commit(F&& f, Args&&... args) ->future<decltype(f(args...))>
  49. {
  50. if (!_run) // stoped ??
  51. throw runtime_error("commit on ThreadPool is stopped.");
  52. using RetType = decltype(f(args...)); // typename std::result_of<F(Args...)>::type, 函数 f 的返回值类型
  53. auto task = make_shared<packaged_task<RetType()>>(
  54. bind(forward<F>(f), forward<Args>(args)...)
  55. ); // 把函数入口及参数,打包(绑定)
  56. future<RetType> future = task->get_future();
  57. { // 添加任务到队列
  58. lock_guard<mutex> lock{ _lock };//对当前块的语句加锁 lock_guard 是 mutex 的 stack 封装类,构造的时候 lock(),析构的时候 unlock()
  59. _tasks.emplace([task](){ // push(Task{...}) 放到队列后面
  60. (*task)();
  61. });
  62. }
  63. #ifdef THREADPOOL_AUTO_GROW
  64. if (_idlThrNum < 1 && _pool.size() < THREADPOOL_MAX_NUM)
  65. addThread(1);
  66. #endif // !THREADPOOL_AUTO_GROW
  67. _task_cv.notify_one(); // 唤醒一个线程执行
  68. return future;
  69. }
  70. //空闲线程数量
  71. int idlCount() { return _idlThrNum; }
  72. //线程数量
  73. int thrCount() { return _pool.size(); }
  74. #ifndef THREADPOOL_AUTO_GROW
  75. private:
  76. #endif // !THREADPOOL_AUTO_GROW
  77. //添加指定数量的线程
  78. void addThread(unsigned short size)
  79. {
  80. for (; _pool.size() < THREADPOOL_MAX_NUM && size > 0; --size)
  81. { //增加线程数量,但不超过 预定义数量 THREADPOOL_MAX_NUM
  82. _pool.emplace_back( [this]{ //工作线程函数
  83. while (_run)
  84. {
  85. Task task; // 获取一个待执行的 task
  86. {
  87. // unique_lock 相比 lock_guard 的好处是:可以随时 unlock() 和 lock()
  88. unique_lock<mutex> lock{ _lock };
  89. _task_cv.wait(lock, [this]{
  90. return !_run || !_tasks.empty();
  91. }); // wait 直到有 task
  92. if (!_run && _tasks.empty())
  93. return;
  94. task = move(_tasks.front()); // 按先进先出从队列取一个 task
  95. _tasks.pop();
  96. }
  97. _idlThrNum--;
  98. task();//执行任务
  99. _idlThrNum++;
  100. }
  101. });
  102. _idlThrNum++;
  103. }
  104. }
  105. };
  106. }
  107. #endif //https://github.com/lzpong/

另一种实现

  1. // A simple thread pool class.
  2. // Usage examples:
  3. //
  4. // {
  5. // ThreadPool pool(16); // 16 worker threads.
  6. // for (int i = 0; i < 100; ++i) {
  7. // pool.Schedule([i]() {
  8. // DoSlowExpensiveOperation(i);
  9. // });
  10. // }
  11. //
  12. // // `pool` goes out of scope here - the code will block in the ~ThreadPool
  13. // // destructor until all work is complete.
  14. // }
  15. //
  16. // // TODO(cbraley): Add examples with std::future.
  17. #include <cassert>
  18. #include <condition_variable>
  19. #include <functional>
  20. #include <future>
  21. #include <mutex>
  22. #include <queue>
  23. #include <thread>
  24. #include <vector>
  25. // This file contains macros that we use to workaround some features that aren't
  26. // available in C++11.
  27. // We want to use std::invoke if C++17 is available, and fallback to "hand
  28. // crafted" code if std::invoke isn't available.
  29. //#if __cplusplus >= 201703L
  30. //#define INVOKE_MACRO(CALLABLE, ARGS_TYPE, ARGS) std::invoke(CALLABLE, std::forward<ARGS_TYPE>(ARGS)...)
  31. //#elif __cplusplus >= 201103L
  32. // Update this with http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4169.html.
  33. #define INVOKE_MACRO(CALLABLE, ARGS_TYPE, ARGS) CALLABLE(std::forward<ARGS_TYPE>(ARGS)...)
  34. //#else
  35. //#error ("C++ version is too old! C++98 is not supported.")
  36. //#endif
  37. namespace cb
  38. {
  39. namespace impl
  40. {
  41. // This helper class simply returns a std::function that executes:
  42. // ReturnT x = func();
  43. // promise->set_value(x);
  44. // However, this is tricky in the case where T == void. The code above won't
  45. // compile if ReturnT == void, and neither will
  46. // promise->set_value(func());
  47. // To workaround this, we use a template specialization for the case where
  48. // ReturnT is void. If the "regular void" proposal is accepted, this could be
  49. // simpler:
  50. // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0146r1.html.
  51. // The non-specialized `FuncWrapper` implementation handles callables that
  52. // return a non-void value.
  53. template <typename ReturnT>
  54. struct FuncWrapper
  55. {
  56. template <typename FuncT, typename... ArgsT>
  57. std::function<void()> GetWrapped(FuncT&& func, std::shared_ptr<std::promise<ReturnT>> promise, ArgsT&&... args)
  58. {
  59. // TODO(cbraley): Capturing by value is inefficient. It would be more
  60. // efficient to move-capture everything, but we can't do this until C++14
  61. // generalized lambda capture is available. Can we use std::bind instead to
  62. // make this more efficient and still use C++11?
  63. return [promise, func, args...]() mutable { promise->set_value(INVOKE_MACRO(func, ArgsT, args)); };
  64. }
  65. };
  66. template <typename FuncT, typename... ArgsT>
  67. void InvokeVoidRet(FuncT&& func, std::shared_ptr<std::promise<void>> promise, ArgsT&&... args)
  68. {
  69. INVOKE_MACRO(func, ArgsT, args);
  70. promise->set_value();
  71. }
  72. // This `FuncWrapper` specialization handles callables that return void.
  73. template <>
  74. struct FuncWrapper<void>
  75. {
  76. template <typename FuncT, typename... ArgsT>
  77. std::function<void()> GetWrapped(FuncT&& func, std::shared_ptr<std::promise<void>> promise, ArgsT&&... args)
  78. {
  79. return [promise, func, args...]() mutable {
  80. INVOKE_MACRO(func, ArgsT, args);
  81. promise->set_value();
  82. };
  83. }
  84. };
  85. } // namespace impl
  86. class ThreadPool
  87. {
  88. public:
  89. // Create a thread pool with `num_workers` dedicated worker threads.
  90. explicit ThreadPool(int num_workers) : num_workers_(num_workers)
  91. {
  92. assert(num_workers_ > 0);
  93. // TODO(cbraley): Handle thread construction exceptions.
  94. workers_.reserve(num_workers);
  95. for (int i = 0; i < num_workers; ++i)
  96. {
  97. workers_.emplace_back(&ThreadPool::ThreadLoop, this);
  98. }
  99. }
  100. // Default construction is disallowed.
  101. ThreadPool() = delete;
  102. // Get the number of logical cores on the CPU. This is implemented using
  103. // std::thread::hardware_concurrency().
  104. // https://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency
  105. static unsigned int GetNumLogicalCores()
  106. {
  107. // TODO(cbraley): Apparently this is broken in some older stdlib
  108. // implementations?
  109. const unsigned int dflt = std::thread::hardware_concurrency();
  110. if (dflt == 0)
  111. {
  112. // TODO(cbraley): Return some error code instead.
  113. return 16;
  114. }
  115. else
  116. {
  117. return dflt;
  118. }
  119. }
  120. // The `ThreadPool` destructor blocks until all outstanding work is complete.
  121. ~ThreadPool()
  122. {
  123. // TODO(cbraley): The current thread could help out to drain the work_ queue
  124. // faster - for example, if there is work that hasn't yet been scheduled this
  125. // thread could "pitch in" to help finish faster.
  126. {
  127. std::lock_guard<std::mutex> scoped_lock(mu_);
  128. exit_ = true;
  129. }
  130. condvar_.notify_all(); // Tell *all* workers we are ready.
  131. for (std::thread& thread : workers_)
  132. {
  133. thread.join();
  134. }
  135. }
  136. // No copying, assigning, or std::move-ing.
  137. ThreadPool& operator=(const ThreadPool&) = delete;
  138. ThreadPool(const ThreadPool&) = delete;
  139. ThreadPool(ThreadPool&&) = delete;
  140. ThreadPool& operator=(ThreadPool&&) = delete;
  141. // Add the function `func` to the thread pool. `func` will be executed at some
  142. // point in the future on an arbitrary thread.
  143. void Schedule(std::function<void(void)> func)
  144. {
  145. ScheduleAndGetFuture(std::move(func)); // We ignore the returned std::future.
  146. }
  147. // Add `func` to the thread pool, and return a std::future that can be used to
  148. // access the function's return value.
  149. //
  150. // *** Usage example ***
  151. // Don't be alarmed by this function's tricky looking signature - this is
  152. // very easy to use. Here's an example:
  153. //
  154. // int ComputeSum(std::vector<int>& values) {
  155. // int sum = 0;
  156. // for (const int& v : values) {
  157. // sum += v;
  158. // }
  159. // return sum;
  160. // }
  161. //
  162. // ThreadPool pool = ...;
  163. // std::vector<int> numbers = ...;
  164. //
  165. // std::future<int> sum_future = ScheduleAndGetFuture(
  166. // []() {
  167. // return ComputeSum(numbers);
  168. // });
  169. //
  170. // // Do other work...
  171. //
  172. // std::cout << "The sum is " << sum_future.get() << std::endl;
  173. //
  174. // *** Details ***
  175. // Given a callable `func` that returns a value of type `RetT`, this
  176. // function returns a std::future<RetT> that can be used to access
  177. // `func`'s results.
  178. template <typename FuncT, typename... ArgsT>
  179. auto ScheduleAndGetFuture(FuncT&& func, ArgsT&&... args) -> std::future<decltype(INVOKE_MACRO(func, ArgsT, args))>
  180. {
  181. using ReturnT = decltype(INVOKE_MACRO(func, ArgsT, args));
  182. // We are only allocating this std::promise in a shared_ptr because
  183. // std::promise is non-copyable.
  184. std::shared_ptr<std::promise<ReturnT>> promise = std::make_shared<std::promise<ReturnT>>();
  185. std::future<ReturnT> ret_future = promise->get_future();
  186. impl::FuncWrapper<ReturnT> func_wrapper;
  187. std::function<void()> wrapped_func =
  188. func_wrapper.GetWrapped(std::forward<FuncT>(func), std::move(promise), std::forward<ArgsT>(args)...);
  189. // Acquire the lock, and then push the WorkItem onto the queue.
  190. {
  191. std::lock_guard<std::mutex> scoped_lock(mu_);
  192. WorkItem work;
  193. work.func = std::move(wrapped_func);
  194. work_.emplace(std::move(work));
  195. }
  196. condvar_.notify_one(); // Tell one worker we are ready.
  197. return ret_future;
  198. }
  199. // Wait for all outstanding work to be completed.
  200. void Wait()
  201. {
  202. std::unique_lock<std::mutex> lock(mu_);
  203. if (!work_.empty())
  204. {
  205. work_done_condvar_.wait(lock, [this] { return work_.empty(); });
  206. }
  207. }
  208. // Return the number of outstanding functions to be executed.
  209. int OutstandingWorkSize() const
  210. {
  211. std::lock_guard<std::mutex> scoped_lock(mu_);
  212. return work_.size();
  213. }
  214. // Return the number of threads in the pool.
  215. int NumWorkers() const { return num_workers_; }
  216. void SetWorkDoneCallback(std::function<void(int)> func) { work_done_callback_ = std::move(func); }
  217. private:
  218. void ThreadLoop()
  219. {
  220. // Wait until the ThreadPool sends us work.
  221. while (true)
  222. {
  223. WorkItem work_item;
  224. int prev_work_size = -1;
  225. {
  226. std::unique_lock<std::mutex> lock(mu_);
  227. condvar_.wait(lock, [this] { return exit_ || (!work_.empty()); });
  228. // ...after the wait(), we hold the lock.
  229. // If all the work is done and exit_ is true, break out of the loop.
  230. if (exit_ && work_.empty())
  231. {
  232. break;
  233. }
  234. // Pop the work off of the queue - we are careful to execute the
  235. // work_item.func callback only after we have released the lock.
  236. prev_work_size = work_.size();
  237. work_item = std::move(work_.front());
  238. work_.pop();
  239. }
  240. // We are careful to do the work without the lock held!
  241. // TODO(cbraley): Handle exceptions properly.
  242. work_item.func(); // Do work.
  243. if (work_done_callback_)
  244. {
  245. work_done_callback_(prev_work_size - 1);
  246. }
  247. // Notify a condvar is all work is done.
  248. {
  249. std::unique_lock<std::mutex> lock(mu_);
  250. if (work_.empty() && prev_work_size == 1)
  251. {
  252. work_done_condvar_.notify_all();
  253. }
  254. }
  255. }
  256. }
  257. // Number of worker threads - fixed at construction time.
  258. int num_workers_;
  259. // The destructor sets `exit_` to true and then notifies all workers. `exit_`
  260. // causes each thread to break out of their work loop.
  261. bool exit_ = false;
  262. mutable std::mutex mu_;
  263. // Work queue. Guarded by `mu_`.
  264. struct WorkItem
  265. {
  266. std::function<void(void)> func;
  267. };
  268. std::queue<WorkItem> work_;
  269. // Condition variable used to notify worker threads that new work is
  270. // available.
  271. std::condition_variable condvar_;
  272. // Worker threads.
  273. std::vector<std::thread> workers_;
  274. // Condition variable used to notify that all work is complete - the work
  275. // queue has "run dry".
  276. std::condition_variable work_done_condvar_;
  277. // Whenever a work item is complete, we call this callback. If this is empty,
  278. // nothing is done.
  279. std::function<void(int)> work_done_callback_;
  280. };
  281. } // namespace cb
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <thread>
  5. #include <mutex>
  6. #include <condition_variable>
  7. #include <functional>
  8. class ThreadPool {
  9. public:
  10. ThreadPool(size_t numThreads) : stop(false) {
  11. for (size_t i = 0; i < numThreads; ++i) {
  12. workers.emplace_back(
  13. [this] {
  14. for (;;) {
  15. std::function<void()> task;
  16. {
  17. std::unique_lock<std::mutex> lock(this->queueMutex);
  18. this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
  19. if (this->stop && this->tasks.empty())
  20. return;
  21. task = std::move(this->tasks.front());
  22. this->tasks.pop();
  23. }
  24. task();
  25. }
  26. }
  27. );
  28. }
  29. }
  30. template <class F>
  31. void enqueue(F&& f) {
  32. {
  33. std::unique_lock<std::mutex> lock(queueMutex);
  34. tasks.emplace(std::forward<F>(f));
  35. }
  36. condition.notify_one();
  37. }
  38. ~ThreadPool() {
  39. {
  40. std::unique_lock<std::mutex> lock(queueMutex);
  41. stop = true;
  42. }
  43. condition.notify_all();
  44. for (std::thread &worker : workers)
  45. worker.join();
  46. }
  47. private:
  48. std::vector<std::thread> workers;
  49. std::queue<std::function<void()>> tasks;
  50. std::mutex queueMutex;
  51. std::condition_variable condition;
  52. bool stop;
  53. };
  54. int main() {
  55. // 创建一个包含4个线程的线程池
  56. ThreadPool pool(4);
  57. // 将任务加入线程池
  58. for (int i = 0; i < 8; ++i) {
  59. pool.enqueue([i] {
  60. std::cout << "Task " << i << " is running\n";
  61. std::this_thread::sleep_for(std::chrono::seconds(1));
  62. std::cout << "Task " << i << " is done\n";
  63. });
  64. }
  65. // 主线程等待所有任务完成
  66. std::this_thread::sleep_for(std::chrono::seconds(5));
  67. return 0;
  68. }

引用:

基于C++11的线程池(threadpool),简洁且可以带任意多的参数 - _Ong - 博客园

c++简单线程池实现 - 渣码农 - 博客园

C++实现线程池_折线式成长的博客-CSDN博客_c++ 线程池

基于C++11实现线程池的工作原理 - 靑い空゛ - 博客园

线程池的C++实现 - 知乎

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/49958?site
推荐阅读
相关标签
  

闽ICP备14008679号

        
cppcmd=keepalive&