21xrx.com
2024-09-20 00:27:16 Friday
登录
文章检索 我的文章 写文章
C++11实现线程池的两种方法
2023-07-04 20:10:07 深夜i     --     --
C++11 线程池 实现方法
return stop_ || !tasks_.empty();

C++11是一种强大的编程语言,为开发者提供了方便且高效的编程工具,其中包括了线程池的实现。本文将介绍C++11实现线程池的两种方法。

1. 使用std::thread库实现线程池

std::thread是C++11新增的线程库,可以实现线程的创建、执行等操作。我们可以通过将任务封装到一个std::function对象中,并放入一个std::queue中,然后从中取出任务并分配给不同的线程运行。以下是使用std::thread实现线程池的示例代码:


#include <iostream>

#include <functional>

#include <queue>

#include <thread>

#include <vector>

#include <mutex>

#include <condition_variable>

using Task = std::function<void()>;

class ThreadPool

{

public:

  ThreadPool(int threadNum = std::thread::hardware_concurrency()) : stop_(false)

  {

    for (int i = 0; i < threadNum; ++i)

    {

      threads_.emplace_back(std::thread(&ThreadPool::worker, this));

    }

  }

  ~ThreadPool()

  {

    {

      std::unique_lock<std::mutex> lock(mutex_);

      stop_ = true;

      cond_.notify_all();

    }

    for (auto& thread : threads_)

    {

      thread.join();

    }

  }

  void addTask(const Task& task)

  {

    std::unique_lock<std::mutex> lock(mutex_);

    tasks_.push(task);

    cond_.notify_one();

  }

private:

  void worker()

  {

    while (!stop_)

    {

      Task task;

      {

        std::unique_lock<std::mutex> lock(mutex_);

        cond_.wait(lock, [this]() { return stop_ || !tasks_.empty(); });

        if (stop_ && tasks_.empty())

        

          return;

        

        task = tasks_.front();

        tasks_.pop();

      }

      task();

    }

  }

private:

  std::vector<std::thread> threads_;

  std::queue<Task> tasks_;

  std::mutex mutex_;

  std::condition_variable cond_;

  bool stop_;

};

2. 使用boost库实现线程池

boost是C++的一个流行的开源库,提供了许多高效的解决方案,其中包括线程池的实现。使用boost库也可以通过将任务封装到一个boost::function对象中,并放入一个boost::lockfree::queue中,然后从中取出任务并分配给不同的线程运行。以下是使用boost库实现线程池的示例代码:


#include <iostream>

#include <boost/lockfree/queue.hpp>

#include <boost/function.hpp>

#include <boost/thread.hpp>

#include <boost/bind.hpp>

using Task = boost::function<void()>;

class ThreadPool

{

public:

  ThreadPool(int threadNum = boost::thread::hardware_concurrency()) : stop_(false)

  {

    for (int i = 0; i < threadNum; ++i)

    {

      threads_.create_thread(boost::bind(&ThreadPool::worker, this));

    }

  }

  ~ThreadPool()

  {

    stop_ = true;

    threads_.join_all();

  }

  void addTask(const Task& task)

  {

    tasks_.push(task);

  }

private:

  void worker()

  {

    while (!stop_)

    {

      Task task;

      if (tasks_.pop(task))

      {

        task();

      }

    }

  }

private:

  boost::thread_group threads_;

  boost::lockfree::queue<Task> tasks_;

  bool stop_;

};

总结:

通过std::thread库和boost库可以方便地实现线程池。使用线程池能够降低程序的开销,提高运行效率。通过封装任务并且为其分配线程,线程池就能够在不同的计算任务中实现高效并发,提高程序的响应速度和稳定性。选择使用哪种拉布来实现线程池,取决于不同的实际应用场景及个人喜好。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复