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;
}
相关推荐
ajassi20004 小时前
开源 C++ QT Widget 开发(十五)多媒体--音频播放
linux·c++·qt·开源
鹅毛在路上了6 小时前
C++, ffmpeg, libavcodec-RTSP拉流,opencv实时预览
c++·opencv·ffmpeg
John_ToDebug6 小时前
定制 ResourceBundle 的实现与 DuiLib 思想在 Chromium 架构下的应用解析
c++·chrome·ui
小欣加油7 小时前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
王璐WL8 小时前
【c++】c++第一课:命名空间
数据结构·c++·算法
aramae8 小时前
C++ -- 模板
开发语言·c++·笔记·其他
MChine慕青10 小时前
顺序表与单链表:核心原理与实战应用
linux·c语言·开发语言·数据结构·c++·算法·链表
骄傲的心别枯萎11 小时前
RV1126 NO.16:通过多线程同时获取H264和H265码流
linux·c++·音视频·rv1126
落羽的落羽11 小时前
【C++】特别的程序错误处理方式——异常机制
开发语言·c++
空山新雨(大队长)12 小时前
C 语言第一课:hello word c
c++·c·exe