• C++线程池实现解析


    一.简介

    progschj/ThreadPool(链接:GitHub - progschj/ThreadPool: A simple C++11 Thread Pool implementation​​​​​​ )是一个用到C++11特性的跨平台线程池,可以在windows,linux上运行。其只用不到100行代码就实现了线程池的基本功能,麻雀虽小五脏俱全,非常适合初学者学习。本文对其源码进行分析。

    二.源码

    ThreadPool.h

    1. #ifndef THREAD_POOL_H
    2. #define THREAD_POOL_H
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. #include
    10. #include
    11. #include
    12. class ThreadPool {
    13. public:
    14. ThreadPool(size_t);
    15. template<class F, class... Args>
    16. auto enqueue(F&& f, Args&&... args)
    17. -> std::future<typename std::result_of<F(Args...)>::type>;
    18. ~ThreadPool();
    19. private:
    20. // need to keep track of threads so we can join them
    21. std::vector< std::thread > workers;
    22. // the task queue
    23. std::queue< std::function<void()> > tasks;
    24. // synchronization
    25. std::mutex queue_mutex;
    26. std::condition_variable condition;
    27. bool stop;
    28. };
    29. // the constructor just launches some amount of workers
    30. inline ThreadPool::ThreadPool(size_t threads)
    31. : stop(false)
    32. {
    33. for(size_t i = 0;i
    34. workers.emplace_back(
    35. [this]
    36. {
    37. for(;;)
    38. {
    39. std::function<void()> task;
    40. {
    41. std::unique_lock lock(this->queue_mutex);
    42. this->condition.wait(lock,
    43. [this]{ return this->stop || !this->tasks.empty(); });
    44. if(this->stop && this->tasks.empty())
    45. return;
    46. task = std::move(this->tasks.front());
    47. this->tasks.pop();
    48. }
    49. task();
    50. }
    51. }
    52. );
    53. }
    54. // add new work item to the pool
    55. template<class F, class... Args>
    56. auto ThreadPool::enqueue(F&& f, Args&&... args)
    57. -> std::future<typename std::result_of<F(Args...)>::type>
    58. {
    59. using return_type = typename std::result_of<F(Args...)>::type;
    60. auto task = std::make_shared< std::packaged_task<return_type()> >(
    61. std::bind(std::forward(f), std::forward(args)...)
    62. );
    63. std::future res = task->get_future();
    64. {
    65. std::unique_lock lock(queue_mutex);
    66. // don't allow enqueueing after stopping the pool
    67. if(stop)
    68. throw std::runtime_error("enqueue on stopped ThreadPool");
    69. tasks.emplace([task](){ (*task)(); });
    70. }
    71. condition.notify_one();
    72. return res;
    73. }
    74. // the destructor joins all threads
    75. inline ThreadPool::~ThreadPool()
    76. {
    77. {
    78. std::unique_lock lock(queue_mutex);
    79. stop = true;
    80. }
    81. condition.notify_all();
    82. for(std::thread &worker: workers)
    83. worker.join();
    84. }
    85. #endif

    使用例子:

    example.cpp

    1. #include
    2. #include
    3. #include
    4. #include "ThreadPool.h"
    5. int main()
    6. {
    7. ThreadPool pool(4);
    8. std::vector< std::future<int> > results;
    9. for(int i = 0; i < 8; ++i) {
    10. results.emplace_back(
    11. pool.enqueue([i] {
    12. std::cout << "hello " << i << std::endl;
    13. std::this_thread::sleep_for(std::chrono::seconds(1));
    14. std::cout << "world " << i << std::endl;
    15. return i*i;
    16. })
    17. );
    18. }
    19. for(auto && result: results)
    20. std::cout << result.get() << ' ';
    21. std::cout << std::endl;
    22. return 0;
    23. }

    三.总流程分析

    上述例子中通过ThreadPool pool(4)创建了4个工作线程,将任务

    1. {
    2. std::cout << "hello " << i << std::endl;
    3. std::this_thread::sleep_for(std::chrono::seconds(1));
    4. std::cout << "world " << i << std::endl;
    5. return i*i;
    6. }

    添加到任务队列(ThreadPool的std::queue< std::function > tasks)中,然后在创建的子线程中启动这些任务。最后通过:

    1. for(auto && result: results)
    2. std::cout << result.get() << ' ';
    3. std::cout << std::endl;

    阻塞等待子线程执行完毕,打印任务的返回值(i*i的结果)。
     

    四.源码分析

    首先我们分析ThreadPool::enqueue函数

    (1)

    1. template<class F, class... Args>
    2. auto ThreadPool::enqueue(F&& f, Args&&... args)
    3. -> std::future<typename std::result_of<F(Args...)>::type>

    template等价于template<typename F, typename... Args>,其中由于有参数class F,所以可以把lambda表达式或函数作为enqueue的第一个参数传进去。class... Args是可变长参数模板,负责把参数传到函数F里面。所以可以在example.cpp中实现:

    1. pool.enqueue([i] {
    2. std::cout << "hello " << i << std::endl;
    3. std::this_thread::sleep_for(std::chrono::seconds(1));
    4. std::cout << "world " << i << std::endl;
    5. return i*i;
    6. }

    上述例子中

    1. [i] {
    2. std::cout << "hello " << i << std::endl;
    3. std::this_thread::sleep_for(std::chrono::seconds(1));
    4. std::cout << "world " << i << std::endl;
    5. return i*i;
    6. }

    是lambda表达式,[i]是捕获列表,表示按值捕获i,所以大括号的代码中可以打印i的值

    可以用函数替换掉lambda表达式作为参数传到enqueue里面,所以上述例子可以改写成:

    1. #include
    2. #include
    3. #include
    4. #include "ThreadPool.h"
    5. int fun(int i)
    6. {
    7. std::cout << "hello " << i << std::endl;
    8. std::this_thread::sleep_for(std::chrono::seconds(1));
    9. std::cout << "world " << i << std::endl;
    10. return i * i;
    11. }
    12. int main()
    13. {
    14. ThreadPool pool(4);
    15. std::vector< std::future<int> > results;
    16. for (int i = 0; i < 8; ++i) {
    17. results.emplace_back(pool.enqueue(fun, i));
    18. }
    19. for(auto && result: results)
    20. std::cout << "get:" << result.get() << std::endl;
    21. //std::cout << std::endl;
    22. return 0;
    23. }

    这里面实参fun对应形参F&& f,实参i对应形参Args&&... args 。

    (2)

    1. template<class F, class... Args>
    2. auto ThreadPool::enqueue(F&& f, Args&&... args)
    3. -> std::future<typename std::result_of<F(Args...)>::type>

    这里的“-> std::future::type>”是返回类型后置,和auto结合起来进行使用,共同完成函数返回值类型的推导,这里enqueue函数的返回值就是std::future::type>。

    由于在example.cpp中

    1. pool.enqueue([i] {
    2. std::cout << "hello " << i << std::endl;
    3. std::this_thread::sleep_for(std::chrono::seconds(1));
    4. std::cout << "world " << i << std::endl;
    5. return i*i;
    6. }

    std::result_of类型。在C++14中可省略箭头返回值部分,直接将函数返回类型设置为auto,所以enqueue函数可以去掉“-> std::future::type>”这部分直接写成:

    auto ThreadPool::enqueue(F&& f, Args&&... args)

    (3)

    using return_type = typename std::result_of<F(Args...)>::type;

    using用来给typename std::result_of::type取别名,相当于typedef

    (4)

    1. auto task = std::make_shared< std::packaged_task<return_type()> >(
    2. std::bind(std::forward(f), std::forward(args)...)
    3. );
    4. std::future res = task->get_future();

    这里创建得到一个packaged_task对象,进而通过它的get_future()成员函数得到已经配对完成的future对象。随后,我们通过ThreadPool::ThreadPool中创建的子线程来执行这个packaged_task,也就是执行线程函数

    1. {
    2. std::cout << "hello " << i << std::endl;
    3. std::this_thread::sleep_for(std::chrono::seconds(1));
    4. std::cout << "world " << i << std::endl;
    5. return i*i;
    6. }

    开始准备结果数据。与此同时,我们在main函数中使用future对象的get()函数

    1. for(auto && result: results)
    2. std::cout << result.get() << ' ';
    3. std::cout << std::endl;

    来等待分支线程执行完毕。一旦分支线程的线程函数执行完毕返回结果数据(return i*i),result数据就会被主线程中的get()函数获得而返回。

    (5)

    1. {
    2. std::unique_lock lock(queue_mutex);
    3. // don't allow enqueueing after stopping the pool
    4. if(stop)
    5. throw std::runtime_error("enqueue on stopped ThreadPool");
    6. tasks.emplace([task](){ (*task)(); });
    7. }
    8. condition.notify_one();

    std::queue< std::function > tasks是任务队列。std::function等价于函数指针,绑定{ (*task)(); }。这里将任务放到任务队列中,为了避免有多个线程同时对tasks进行操作,所以这里得加锁std::unique_lock lock(queue_mutex),保证在任一时刻,只能有一个线程访问它。然后通过condition.notify_one() 通知ThreadPool::ThreadPool中第一个进入阻塞或者等待的线程,取消对线程的阻塞。

    我们接着分析inline ThreadPool::ThreadPool(size_t threads)函数

    (6)

    1. for(size_t i = 0;i
    2. workers.emplace_back(
    3. ...

    通过这里创建了threads个子线程

    (7)

    1. {
    2. std::unique_lock lock(this->queue_mutex);
    3. this->condition.wait(lock,
    4. [this]{ return this->stop || !this->tasks.empty(); });
    5. if(this->stop && this->tasks.empty())
    6. return;
    7. .....

    这里通过条件变量,让任务队列为空的时候可以阻塞,避免不断轮询判断缓冲区是否为空消耗CPU。

    (8)

    1. task = std::move(this->tasks.front());
    2. this->tasks.pop();

    这里把任务出队列。其用到了移动赋值,避免拷贝,提高了性能。

    (9)

    task();

    这里相当于执行了[task](){ (*task)(); }。而(*task)()执行了主函数

    1. {
    2. std::cout << "hello " << i << std::endl;
    3. std::this_thread::sleep_for(std::chrono::seconds(1));
    4. std::cout << "world " << i << std::endl;
    5. return i*i;
    6. }

    中的内容,从而实现了在子线程中执行任务

  • 相关阅读:
    Qt图像处理技术九:得到QImage图像的灰度直方图
    充气膜建筑的形体设计
    一文看懂推荐系统:经典双塔模型:微软DSSM模型(Deep Structured Semantic Models),无特征交互,后来美团改进了
    Python物联网开发-Python_Socket通信开发-Python与Tcp协议物联网设备通信-Socket客户端
    2024年腾讯云8核16G18M服务器租用价格1668元15个月
    [SpringBoot] @Value 与 @ConfigurationProperties 对比
    代码随想录算法训练营第60天(动态规划17● 647. 回文子串 ● 516.最长回文子序列 ● 动态规划总结篇
    C++面向对象三大特性之一------继承
    数据链路层——MAC地址欺骗及泛洪
    Redis 限流的 3 种方式,还有谁不会
  • 原文地址:https://blog.csdn.net/u014552102/article/details/127438016