ToB企服应用市场:ToB评测及商务社交产业平台

标题: 【C++11】多线程常用知识 [打印本页]

作者: 花瓣小跑    时间: 2024-6-11 12:41
标题: 【C++11】多线程常用知识
知识体系


thread

C++ thread中最常用的两个函数是join和detach,怎么选择呢,简单来说,假如盼望等候线程结束,用join,假如盼望异步执行,且不等候执行结果,那么就用detach;thread_local可以简单理解为一个线程级别的全局变量;线程id在调试多线程程序时黑白常有用的东西;
C++11本身没有提供线程池;可以参考第三方的实现:https://github.com/progschj/ThreadPool
  1. #ifndef THREAD_POOL_H
  2. #define THREAD_POOL_H
  3. #include <vector>
  4. #include <queue>
  5. #include <memory>
  6. #include <thread>
  7. #include <mutex>
  8. #include <condition_variable>
  9. #include <future>
  10. #include <functional>
  11. #include <stdexcept>
  12. class ThreadPool {
  13.    
  14. public:
  15.     ThreadPool(size_t);
  16.     template<class F, class... Args>
  17.     auto enqueue(F&& f, Args&&... args)
  18.         -> std::future<typename std::result_of<F(Args...)>::type>;
  19.     ~ThreadPool();
  20. private:
  21.     // need to keep track of threads so we can join them
  22.     std::vector< std::thread > workers;
  23.     // the task queue
  24.     std::queue< std::function<void()> > tasks;
  25.    
  26.     // synchronization
  27.     std::mutex queue_mutex;
  28.     std::condition_variable condition;
  29.     bool stop;
  30. };
  31. // the constructor just launches some amount of workers
  32. inline ThreadPool::ThreadPool(size_t threads)
  33.     :   stop(false)
  34. {
  35.    
  36.     for(size_t i = 0;i<threads;++i)
  37.         workers.emplace_back(
  38.             [this]
  39.             {
  40.    
  41.                 for(;;)
  42.                 {
  43.    
  44.                     std::function<void
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4