21xrx.com
2024-09-20 06:41:56 Friday
登录
文章检索 我的文章 写文章
C++简单线程池实现
2023-07-09 22:39:53 深夜i     --     --
C++ 线程池 简单实现
return this->stop || !this->tasks_.empty();

在C++中,线程池是一种常见的设计模式,它可以大大提高程序的并发性能并减轻线程创建和销毁所带来的开销。

本文介绍一种基本的C++线程池实现,代码简单易懂,适合初学者学习。

线程池主要由以下几个元素组成:

1. 任务队列:用于存储需要执行的任务。

2. 线程队列:用于存储可用的线程。

3. 线程池管理器:调度任务和管理线程池。

代码实现如下:


#include <iostream>

#include <queue>

#include <thread>

#include <mutex>

#include <condition_variable>

#include <functional>

using namespace std;

class ThreadPool {

public:

  ThreadPool(int threads = 4) : stop(false) {

    for (int i = 0; i < threads; ++i) {

      threads_.emplace_back(

        [this] {

          for (;;) {

            std::function<void()> task;

            {

              std::unique_lock<std::mutex> lock(this->queue_mutex);

              this->condition.wait(lock,

                         [this] { return this->stop || !this->tasks_.empty(); });

              if (this->stop && this->tasks_.empty())

                return;

              task = std::move(this->tasks_.front());

              this->tasks_.pop();

            }

            task();

          }

        }

      );

    }

  }

  template<class 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& thread : threads_)

      thread.join();

  }

private:

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

  std::queue<std::function<void()>> tasks_;

  std::mutex queue_mutex;

  std::condition_variable condition;

  bool stop;

};

在该实现中,构造函数接收线程数并创建相应数量的线程,这些线程会一直执行直到析构函数被调用或stop标记被设置为true。

`enqueue`函数用于添加任务到队列中,并使用条件变量唤醒线程来执行任务。

`~ThreadPool`函数会先设置stop标记为true并发出条件变量的所有信号,然后使用join()等待所有线程结束。

使用该线程池非常简单,只需添加需要执行的任务到线程池中即可:


ThreadPool pool(4);

// 添加任务

pool.enqueue([]

  cout << "Hello);

pool.enqueue([]

  cout << "World!" << endl;

);

总结:

本文介绍了一种简单易懂的C++线程池实现,学习者可以根据需要自由组织代码并进行拓展,为自己的程序提供高性能的并发支持。

  
  

评论区

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