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