#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;
}