CPP线程管理类实现

一个线程管理模块应该包含Task(任务类)、Thread(线程类)、线程管理类(ThreadManager)。

cpp 复制代码
#pragma once
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <queue>
#include <functional>
#include <condition_variable>

typedef std::function<void(void*)> ThreadTaskFun;

// 任务类
class Task {
public:
  Task(ThreadTaskFun, void* param = nullptr) : func_(std::move(func)), taskParams(param){}
  Task() {}

  void execute() {
    if (func_) {
      func_(taskParams);
    }
  }

private:
  std::function<void(void*)> func_;
  void* taskParams;
};

// 线程类
class Thread {
public:
  Thread() : thread_(), active_(false) {}

  void start() {
    active_ = true;
    thread_ = std::thread([this]() {
      while (active_) {
        Task task;
        {
          std::unique_lock<std::mutex> lock(mutex_);
          // 等待任务队列不为空
          condition_.wait(lock, [this]() { return !tasks_.empty() || !active_; });
          if (!active_) {
            break;
          }
          task = std::move(tasks_.front());
          tasks_.pop();
        }
        task.execute();
      }
    });
  }

  void stop() {
    if (active_) {
      active_ = false;
      condition_.notify_one();
      if (thread_.joinable()) {
        thread_.join();
      }
    }
  }

  void addTask(Task task) {
    std::lock_guard<std::mutex> lock(mutex_);
    tasks_.push(std::move(task));
    condition_.notify_one();
  }

private:
  std::thread thread_;
  std::queue<Task> tasks_;
  std::mutex mutex_;
  std::condition_variable condition_;
  bool active_;
};

// 线程管理类
class ThreadManager {
public:
  ThreadManager(int num_threads) {
    for (int i = 0; i < num_threads; ++i) {
      threads_.emplace_back(std::make_unique<Thread>());
    }
  }

  ~ThreadManager()
  {
    stopThreads();
  }

  void startThreads() {
    for (auto& thread : threads_) {
      thread->start();
    }
  }

  void stopThreads() {
    for (auto& thread : threads_) {
      thread->stop();
    }
  }

  void addTask(Task task) {
    if (index_ >= threads_.size()) {
      index_ = 0; // 循环使用线程
    }
    threads_[index_]->addTask(std::move(task));
    index_++;
  }

private:
  std::vector<std::unique_ptr<Thread>> threads_;
  int index_ = 0;
};

Demo

cpp 复制代码
#include "threadpool.h"

class Resources
{
public:
  Resources()
  {
    resourcesThreadFun = std::bind(&Resources::exampleTaskFunction, this, std::placeholders::_1);
  }
  void exampleTaskFunction(void* param) {
    int index = 0;
    std::cout << "Executing task " << index << " in thread: " << std::this_thread::get_id() << std::endl;
  }

  ThreadTaskFun resourcesThreadFun;

};

int main() {
  ThreadManager manager(4); // 创建4个线程
  manager.startThreads();

  Resources* pResource = new Resources();
  

  // 添加10个示例任务
  for (int i = 0; i < 100; ++i) {
    Task task(pResource->resourcesThreadFun);
    manager.addTask(std::move(task));
  }

  std::cout << "main thread over!" << std::endl;

  return 0;
}
相关推荐
lihao lihao12 小时前
C++ set和map
开发语言·c++·算法
学嵌入式的小杨同学12 小时前
顺序表(SqList)完整解析与实现(数据结构专栏版)
c++·算法·unity·游戏引擎·代理模式
我就想睡到自然醒12 小时前
【C++基础STL1】数组和vector
c++
玖釉-12 小时前
[Vulkan 学习之路] 04 - 选妃环节:挑选物理设备与队列族
c++·windows·图形渲染
三万棵雪松12 小时前
【AI小智硬件程序(九)】
c++·人工智能·嵌入式·esp32·ai小智
HABuo12 小时前
【linux进程控制(一)】进程创建&退出-->fork&退出码详谈
linux·运维·服务器·c语言·c++·ubuntu·centos
想唱rap13 小时前
MySQL内置函数
linux·运维·服务器·数据库·c++·mysql
玖釉-13 小时前
[Vulkan 学习之路] 10 - 掌握 SPIR-V:编写你的第一个着色器 (Shader Modules)
c++·windows·图形渲染
xiaoye-duck13 小时前
吃透C++类和对象(中):详解 Date 类的设计与实现
c++
玖釉-13 小时前
[Vulkan 学习之路] 03 - 你的守护天使:校验层 (Validation Layers)
c++·windows·图形渲染