|
ThreadPool.h
- #ifndef THREADPOOL_H
- #define THREADPOOL_H
- #include <vector>
- #include <queue>
- #include <thread>
- #include <mutex>
- #include <condition_variable>
- #include <future>
- #include <functional>
- #include <stdexcept>
- class ThreadPool {
- public:
- ThreadPool(size_t threads) : stop(false) {
- for (size_t i = 0; i < threads; ++i)
- workers.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();
- }
- }
- );
- }
- ~ThreadPool() {
- {
- std::unique_lock<std::mutex> lock(queue_mutex);
- stop = true;
- }
- condition.notify_all();
- for (std::thread& worker : workers)
- worker.join();
- }
- template<class F, class... Args>
- auto enqueue(F&& f, Args&&... args)
- -> std::future<typename std::result_of<F(Args...)>::type> {
- using return_type = typename std::result_of<F(Args...)>::type;
- auto task = std::make_shared< std::packaged_task<return_type()> >(
- std::bind(std::forward<F>(f), std::forward<Args>(args)...)
- );
- std::future<return_type> res = task->get_future();
- {
- std::unique_lock<std::mutex> lock(queue_mutex);
- if (stop)
- throw std::runtime_error("enqueue on stopped ThreadPool");
- tasks.emplace([task]() { (*task)(); });
- }
- condition.notify_one();
- return res;
- }
- private:
- std::vector< std::thread > workers;
- std::queue< std::function<void()> > tasks;
- std::mutex queue_mutex;
- std::condition_variable condition;
- bool stop;
- };
- #endif
複製代碼 main.cpp
- #include "ThreadPool.h"
- #include <iostream>
- #include <vector>
- #include <chrono>
- #include <random>
- struct TaskInfo {
- int id;
- std::chrono::milliseconds start_time;
- std::chrono::milliseconds end_time;
- double duration() const {
- return std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count() / 1000.0;
- }
- };
- int main() {
- ThreadPool pool(10); // 使用10个线程的线程池
- std::vector<TaskInfo> taskInfos(10);
- std::vector<std::future<void>> results;
- auto start = std::chrono::high_resolution_clock::now();
- for (int i = 0; i < 10; ++i) {
- results.emplace_back(
- pool.enqueue([i, &taskInfos, start]() {
- auto task_start = std::chrono::high_resolution_clock::now();
- // 模拟工作负载
- std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 假设每个任务需要100毫秒
- auto task_end = std::chrono::high_resolution_clock::now();
- taskInfos[i] = { i, std::chrono::duration_cast<std::chrono::milliseconds>(task_start - start),
- std::chrono::duration_cast<std::chrono::milliseconds>(task_end - start) };
- // 此处可以添加打印任务完成信息的代码
- std::cout << "Task" << i << " over!" << std::endl;
- })
- );
- }
- // 确保所有任务已经完成
- for (auto& res : results) {
- res.get();
- }
- auto overall_end = std::chrono::high_resolution_clock::now();
- // 分析任务执行时间,找出最快和最慢的任务
- auto minmax = std::minmax_element(taskInfos.begin(), taskInfos.end(), [](const TaskInfo& a, const TaskInfo& b) {
- return a.duration() < b.duration();
- });
- // 输出最快和最慢的任务信息
- if (minmax.first != taskInfos.end() && minmax.second != taskInfos.end()) {
- std::cout << "most fast #" << minmax.first->id << ", used: " << minmax.first->duration() << " ms" << std::endl;
- std::cout << "most slow #" << minmax.second->id << ", used: " << minmax.second->duration() << " ms" << std::endl;
- }
- // 输出整体执行时间
- auto total_duration = std::chrono::duration_cast<std::chrono::milliseconds>(overall_end - start).count();
- std::cout << "all complete! total used: " << total_duration << " ms" << std::endl;
- }
複製代碼
|
|