登錄 |創建賬號 |找回密碼
查看: 77|回復: 0

windows多线程demo-20240324

[複製鏈接]

23

主題

6

回帖

128

積分

管理員

Rank: 9Rank: 9Rank: 9

積分
128
發表於 2024-3-24 20:32:52 | 顯示全部樓層 |閱讀模式
ThreadPool.h

  1. #ifndef THREADPOOL_H
  2. #define THREADPOOL_H

  3. #include <vector>
  4. #include <queue>
  5. #include <thread>
  6. #include <mutex>
  7. #include <condition_variable>
  8. #include <future>
  9. #include <functional>
  10. #include <stdexcept>

  11. class ThreadPool {
  12. public:
  13.     ThreadPool(size_t threads) : stop(false) {
  14.         for (size_t i = 0; i < threads; ++i)
  15.             workers.emplace_back(
  16.                 [this] {
  17.                     for (;;) {
  18.                         std::function<void()> task;

  19.                         {
  20.                             std::unique_lock<std::mutex> lock(this->queue_mutex);
  21.                             this->condition.wait(lock,
  22.                                 [this] { return this->stop || !this->tasks.empty(); });
  23.                             if (this->stop && this->tasks.empty())
  24.                                 return;
  25.                             task = std::move(this->tasks.front());
  26.                             this->tasks.pop();
  27.                         }

  28.                         task();
  29.                     }
  30.                 }
  31.         );
  32.     }

  33.     ~ThreadPool() {
  34.         {
  35.             std::unique_lock<std::mutex> lock(queue_mutex);
  36.             stop = true;
  37.         }
  38.         condition.notify_all();
  39.         for (std::thread& worker : workers)
  40.             worker.join();
  41.     }

  42.     template<class F, class... Args>
  43.     auto enqueue(F&& f, Args&&... args)
  44.         -> std::future<typename std::result_of<F(Args...)>::type> {
  45.         using return_type = typename std::result_of<F(Args...)>::type;

  46.         auto task = std::make_shared< std::packaged_task<return_type()> >(
  47.             std::bind(std::forward<F>(f), std::forward<Args>(args)...)
  48.         );

  49.         std::future<return_type> res = task->get_future();
  50.         {
  51.             std::unique_lock<std::mutex> lock(queue_mutex);

  52.             if (stop)
  53.                 throw std::runtime_error("enqueue on stopped ThreadPool");

  54.             tasks.emplace([task]() { (*task)(); });
  55.         }
  56.         condition.notify_one();
  57.         return res;
  58.     }

  59. private:
  60.     std::vector< std::thread > workers;
  61.     std::queue< std::function<void()> > tasks;
  62.     std::mutex queue_mutex;
  63.     std::condition_variable condition;
  64.     bool stop;
  65. };

  66. #endif
複製代碼
main.cpp
  1. #include "ThreadPool.h"
  2. #include <iostream>
  3. #include <vector>
  4. #include <chrono>
  5. #include <random>

  6. struct TaskInfo {
  7.     int id;
  8.     std::chrono::milliseconds start_time;
  9.     std::chrono::milliseconds end_time;
  10.     double duration() const {
  11.         return std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count() / 1000.0;
  12.     }
  13. };

  14. int main() {
  15.     ThreadPool pool(10); // 使用10个线程的线程池

  16.     std::vector<TaskInfo> taskInfos(10);
  17.     std::vector<std::future<void>> results;

  18.     auto start = std::chrono::high_resolution_clock::now();

  19.     for (int i = 0; i < 10; ++i) {
  20.         results.emplace_back(
  21.             pool.enqueue([i, &taskInfos, start]() {
  22.                 auto task_start = std::chrono::high_resolution_clock::now();

  23.                 // 模拟工作负载
  24.                 std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 假设每个任务需要100毫秒

  25.                 auto task_end = std::chrono::high_resolution_clock::now();

  26.                 taskInfos[i] = { i, std::chrono::duration_cast<std::chrono::milliseconds>(task_start - start),
  27.                                 std::chrono::duration_cast<std::chrono::milliseconds>(task_end - start) };

  28.                 // 此处可以添加打印任务完成信息的代码
  29.                 std::cout << "Task" << i << " over!" << std::endl;
  30.                 })
  31.         );
  32.     }

  33.     // 确保所有任务已经完成
  34.     for (auto& res : results) {
  35.         res.get();
  36.     }

  37.     auto overall_end = std::chrono::high_resolution_clock::now();

  38.     // 分析任务执行时间,找出最快和最慢的任务
  39.     auto minmax = std::minmax_element(taskInfos.begin(), taskInfos.end(), [](const TaskInfo& a, const TaskInfo& b) {
  40.         return a.duration() < b.duration();
  41.         });

  42.     // 输出最快和最慢的任务信息
  43.     if (minmax.first != taskInfos.end() && minmax.second != taskInfos.end()) {
  44.         std::cout << "most fast #" << minmax.first->id << ", used: " << minmax.first->duration() << " ms" << std::endl;
  45.         std::cout << "most slow #" << minmax.second->id << ", used: " << minmax.second->duration() << " ms" << std::endl;
  46.     }

  47.     // 输出整体执行时间
  48.     auto total_duration = std::chrono::duration_cast<std::chrono::milliseconds>(overall_end - start).count();
  49.     std::cout << "all complete! total used: " << total_duration << " ms" << std::endl;
  50. }
複製代碼


回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 創建賬號

本版積分規則

Archiver|手機版|小黑屋|九派社區 ( 苏ICP备07501547号-12 )

GMT+8, 2024-5-17 08:22 , Processed in 0.099348 second(s), 27 queries .

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回復 返回頂部 返回列表