您的位置:首页 > 科技 > IT业 > 前端开发的工作内容_电商网站建设需要多少钱_昆明百度推广开户费用_网站建设与营销经验

前端开发的工作内容_电商网站建设需要多少钱_昆明百度推广开户费用_网站建设与营销经验

2024/9/25 1:16:30 来源:https://blog.csdn.net/jjjxxxhhh123/article/details/142456023  浏览:    关键词:前端开发的工作内容_电商网站建设需要多少钱_昆明百度推广开户费用_网站建设与营销经验
前端开发的工作内容_电商网站建设需要多少钱_昆明百度推广开户费用_网站建设与营销经验
#include <iostream>
#include <queue>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <memory>
#include <future>class ThreadPool {
public:static ThreadPool& getInstance(size_t threads = 4) {static ThreadPool instance(threads);return instance;}// 禁用拷贝构造和赋值操作符,确保单例ThreadPool(const ThreadPool&) = delete;ThreadPool& operator=(const ThreadPool&) = delete;// 提交任务到线程池template<class F, class... Args>auto submit(F&& f, Args&&... args) -> std::future<decltype(f(args...))> {using return_type = decltype(f(args...));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(m_queue_mutex);m_tasks.emplace([task]() { (*task)(); });}m_condition.notify_one();return res;}// 关闭线程池并等待所有线程完成任务void shutdown() {{std::unique_lock<std::mutex> lock(m_queue_mutex);m_stop = true;}m_condition.notify_all();for (std::thread &worker : m_workers) {worker.join();}}private:// 构造函数私有化,单例模式ThreadPool(size_t threads) : m_stop(false) {for (size_t i = 0; i < threads; ++i) {m_workers.emplace_back([this] {for (;;) {std::function<void()> task;{std::unique_lock<std::mutex> lock(m_queue_mutex);m_condition.wait(lock, [this] { return m_stop || !m_tasks.empty(); });if (m_stop && m_tasks.empty())return;task = std::move(m_tasks.front());m_tasks.pop();}task();}});}}~ThreadPool() {shutdown();}// 线程池中的线程和任务队列std::vector<std::thread> m_workers;std::queue<std::function<void()>> m_tasks;// 同步机制std::mutex m_queue_mutex;std::condition_variable m_condition;bool m_stop;
};// 模拟的任务类
class TaskManager {
public:void performTask() {std::cout << "Task is running on thread: " << std::this_thread::get_id() << std::endl;}void run() {ThreadPool& pool = ThreadPool::getInstance();auto result = pool.submit(&TaskManager::performTask, this);result.get();  // 等待任务完成}
};int main() {TaskManager task1;TaskManager task2;task1.run();task2.run();ThreadPool::getInstance().shutdown(); // 关闭线程池return 0;
}

版权声明:

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

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