【C++11】多线程常用知识

打印 上一主题 下一主题

主题 512|帖子 512|积分 1536

知识体系


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企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

花瓣小跑

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表