单例模式的线程池c++
时间: 2024-01-25 13:03:22 浏览: 72
以下是一个使用单例模式实现的线程池的C++示例:
```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
static ThreadPool& getInstance() {
static ThreadPool instance;
return instance;
}
void addTask(std::function<void()> task) {
std::unique_lock<std::mutex> lock(mutex_);
tasks_.push(task);
condition_.notify_one();
}
private:
ThreadPool() {
int numThreads = std::thread::hardware_concurrency();
for (int i = 0; i < numThreads; ++i) {
threads_.emplace_back([this]() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mutex_);
condition_.wait(lock, [this]() {
return !tasks_.empty();
});
task = tasks_.front();
tasks_.pop();
}
task();
}
});
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(mutex_);
stop_ = true;
}
condition_.notify_all();
for (std::thread& thread : threads_) {
thread.join();
}
}
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
private:
std::vector<std::thread> threads_;
std::queue<std::function<void()>> tasks_;
std::mutex mutex_;
std::condition_variable condition_;
bool stop_ = false;
};
// 使用示例
void task1() {
std::cout << "Task 1 executed" << std::endl;
}
void task2() {
std::cout << "Task 2 executed" << std::endl;
}
int main() {
ThreadPool& threadPool = ThreadPool::getInstance();
threadPool.addTask(task1);
threadPool.addTask(task2);
// 等待任务执行完成
std::this_thread::sleep_for(std::chrono::seconds(1));
return 0;
}
```
阅读全文