首页 > 后端开发 > C++ > 正文

C++并发编程:如何进行任务调度和线程池管理?

WBOY
发布: 2024-05-06 10:15:02
原创
955 人浏览过

任务调度和线程池管理是 C 并发编程中提高效率和可扩展性的关键。任务调度:使用 std::thread 创建新线程。使用 join() 方法加入线程。线程池管理:创建 ThreadPool 对象,指定线程数量。使用 add_task() 方法添加任务。调用 join() 或 stop() 方法关闭线程池。

C++并发编程:如何进行任务调度和线程池管理?

C 并发编程:任务调度和线程池管理

简介

在并发编程中,任务调度和线程池管理对于提高应用程序的效率和可扩展性至关重要。本文将引导您了解 C 中任务调度的概念,并展示如何使用 C 11 标准中的 std::threadstd::mutex 来管理线程池。

任务调度

任务调度涉及分配和执行异步任务。在 C 中,可以使用 std::thread 来创建新线程:

std::thread t([]() {
  // 执行异步任务
});
登录后复制

要加入线程,请使用 join() 方法:

t.join();
登录后复制

线程池管理

线程池是一个预先创建并管理的线程集合,可用于处理任务。使用线程池可以避免反复创建和销毁线程的开销。

以下是如何在 C 中创建和管理线程池:

class ThreadPool {
public:
  ThreadPool(int num_threads) {
    for (int i = 0; i < num_threads; i++) {
      threads_.emplace_back(std::thread([this]() { this->thread_loop(); }));
    }
  }

  void thread_loop() {
    while (true) {
      std::function<void()> task;

      {
        std::lock_guard<std::mutex> lock(mtx_);
        if (tasks_.empty()) {
          continue;
        }

        task = tasks_.front();
        tasks_.pop();
      }

      task();
    }
  }

  void add_task(std::function<void()> task) {
    std::lock_guard<std::mutex> lock(mtx_);
    tasks_.push(task);
  }

  void stop() {
    std::unique_lock<std::mutex> lock(mtx_);
    stop_ = true;
  }

  ~ThreadPool() {
    stop();

    for (auto& t : threads_) {
      t.join();
    }
  }

private:
  std::vector<std::thread> threads_;
  std::queue<std::function<void()>> tasks_;
  std::mutex mtx_;
  bool stop_ = false;
};
登录后复制

要使用线程池,可以执行以下步骤:

  1. 创建一个线程池对象,指定要创建的线程数。
  2. 使用 add_task() 方法将任务添加到线程池。
  3. 调用 join()stop() 方法来关闭线程池并等待所有任务完成。

实战案例

以下是一个使用线程池在多核系统上执行并发任务的示例:

#include <iostream>
#include <vector>
#include "thread_pool.h"

int main() {
  ThreadPool pool(4);

  std::vector<std::future<int>> futures;
  for (int i = 0; i < 10000; i++) {
    futures.push_back(pool.add_task([i]() { return i * i; }));
  }

  for (auto& f : futures) {
    std::cout << f.get() << std::endl;
  }

  return 0;
}
登录后复制

结论

通过使用 std::thread 和线程池,可以有效地管理 C 中的并发任务。无论是多核系统上的科学计算还是需要处理大量请求的 Web 服务,线程调度和线程池管理都是提高代码效率和可扩展性的关键。

以上是C++并发编程:如何进行任务调度和线程池管理?的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!