21xrx.com
2025-03-23 02:00:56 Sunday
文章检索 我的文章 写文章
"C++11、14、17、20多线程:从原理到线程池实战"
2023-06-22 05:42:39 深夜i     --     --
C++ 多线程 C++11 14 17 20 原理 线程池实战 实践

在现代软件系统中,多线程并发已经成为越来越常用的技术实践。C++作为一门优秀的编程语言,在版本更新中也不断地提供了更好的多线程支持。本文将介绍C++11、14、17、20多线程的原理及其在线程池实战中的应用。

C++11是C++标准委员会在2011年发布的一个重要版本,其中最引人注目的特性是多线程支持。在C++11之前,C++标准库并没有为多线程提供原生支持。开发人员必须使用操作系统提供的接口或第三方库来实现多线程。C++11引入了std :: thread类、互斥量和条件变量等语言特性,使得C++标准库具有了原生的多线程支持。

C++14对多线程的支持进行了增强,包括了对std :: thread的优化、对互斥量和条件变量的改进,以及对原子操作的扩展。此外,C++14还引入了通用 lambda,让编写多线程程序更方便。

C++17在多线程方面引入了更多改进,包括新增std :: shared_mutex、std :: jthread类。其中std :: shared_mutex是一个可多次读取单一获得者互斥量,而std :: jthread是一个智能指针,可自动结束线程。

C++20中的多线程支持进一步提升了多线程编程的易用性和性能。新的库包括std :: latch、std :: barrier、std :: stop_token类等,可让开发人员更有效地进行线程同步和防止单线程空转达成多线程处理。

在实际应用中,C++标准库中的多线程支持可以用来实现许多常见的并发模式,其中包括线程池。线程池是一种并发模式,它可以限制线程的数量并重用线程,从而提高并发性能。线程池包括线程池调度器和线程工作者。调度器负责管理线程池中的线程,分配任务和通知线程工作者完成任务。线程工作者则负责执行分配的任务。

下面是一个使用C++11线程的线程池实例代码:

#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
template <typename T>
class ThreadPool {
public:
  ThreadPool(size_t threads) : stop(false)
  {
    for (size_t i = 0; i < threads; ++i)
      workers.emplace_back(
        [this]
        {
          for(;;)
          {
            std::unique_lock<std::mutex> lock(this->queue_mutex);
            while(!this->stop && this->tasks.empty())
              this->condition.wait(lock);
            if(this->stop && this->tasks.empty())
              return;
            auto task = std::move(this->tasks.front());
            this->tasks.pop();
            lock.unlock();
            task();
          }
        }
      );
  }
  template <typename F>
  void enqueue(F&& f)
  {
    {
      std::unique_lock<std::mutex> lock(queue_mutex);
      tasks.emplace(std::forward<F>(f));
    }
    condition.notify_one();
  }
  ~ThreadPool()
  {
    {
      std::unique_lock<std::mutex> lock(queue_mutex);
      stop = true;
    }
    condition.notify_all();
    for (std::thread& worker: workers)
      worker.join();
  }
private:
  std::vector<std::thread> workers;
  std::queue<std::function<void()>> tasks;
  std::mutex queue_mutex;
  std::condition_variable condition;
  bool stop;
};
void func() {
  std::this_thread::sleep_for(std::chrono::milliseconds(100));
  std::cout << "Hi from thread " << std::this_thread::get_id() << std::endl;
}
int main() {
  ThreadPool pool(4);
  for(int i = 0; i < 8; ++i) {
    pool.enqueue([]{ func(); });
  }
  return 0;
}

在上述示例中,ThreadPool类是一个简单的线程池实现。当使用ThreadPool加入一个任务时,ThreadPool将任务加入任务队列,并通知线程工作者开始工作。在线程工作者内部,根据任务队列的情况完成任务的处理。

通过以上C++11代码,我们可以看到,C++11多线程的使用非常方便。而C++14、17、20中的多线程特性也在不断进化,不断优化多线程编程的效率和性能,可以更好地适应现代软件开发的需求,提升程序的并发性和实时性。

  
  

评论区

    相似文章