您的位置:首页 > 游戏 > 游戏 > 北京网页游戏制作_有效的网络营销方式_安卓手机优化_seo推广灰色词

北京网页游戏制作_有效的网络营销方式_安卓手机优化_seo推广灰色词

2024/12/22 21:44:40 来源:https://blog.csdn.net/hss2799/article/details/144558718  浏览:    关键词:北京网页游戏制作_有效的网络营销方式_安卓手机优化_seo推广灰色词
北京网页游戏制作_有效的网络营销方式_安卓手机优化_seo推广灰色词

模拟场景

执行1000个任务,最大50个线程

定义一个任务类


#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <memory>
#include <atomic>
#include <iostream>
#include <thread>
#include <sstream>//执行任务类
class Task {
public:explicit Task(int taskId) : taskId(taskId) {}int operator()() {std::ostringstream oss;oss << std::this_thread::get_id() << "-> Task " << taskId << std::endl;std::cout << oss.str();std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟任务耗时return taskId + 5000; // 比如执行 结果 + 5000}private:int taskId;
};

实现线程池


// 线程池
class ThreadPool {
public:explicit ThreadPool(size_t threadCount) : stop(false) {for (size_t i = 0; i < threadCount; ++i) {workers.emplace_back([this]() {while (true) {std::function<void()> task;{std::unique_lock<std::mutex> lock(queueMutex);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(); // 执行任务++tasksCompleted; // 增加已完成任务计数std::ostringstream oss;oss << std::this_thread::get_id() << " -> Progress: " << tasksCompleted << " out of " << totalTasks << " tasks completed." << std::endl;std::cout << oss.str() ;}});}}template <typename F, typename... 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(queueMutex);if (stop) {throw std::runtime_error("enqueue on stopped ThreadPool");}tasks.emplace([task]() { (*task)(); });++totalTasks;  // 增加总任务计数}condition.notify_one();return res;}~ThreadPool() {{std::unique_lock<std::mutex> lock(queueMutex);stop = true;}condition.notify_all();for (std::thread& worker : workers) {worker.join();}}private:std::vector<std::thread> workers;       //执行线程std::queue<std::function<void()>> tasks;//执行任务std::mutex queueMutex;std::condition_variable condition;bool stop;  //停止线程池std::atomic<size_t> tasksCompleted{ 0 }; //完成数量std::atomic<size_t> totalTasks{ 0 };    // 总数量
};

调用线程池


int main() {// 最大线程数量const size_t maxThreads = 50;// 一批任务数量const size_t totalTasks = 1000;ThreadPool pool(maxThreads);// 将任务 添加到线程池中执行std::vector<std::future<int>> results;for (int i = 0; i < totalTasks; ++i) {results.emplace_back(pool.enqueue(Task(i)));}std::vector<int> taskResults;  // 存储所有任务的结果for (auto& result : results) {taskResults.push_back(result.get());  // 获取每个任务的结果并存储}std::cout << "All tasks completed!" << std::endl;for (const auto& res : taskResults) {std::cout << res << " ";  // 输出所有任务的结果}std::cout << std::endl;return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com