VC++实现线程池的示例代码
VC++实现线程池的示例代码使用 VC++ 实现线程池的示例代码。这个线程池可以用于管理多个线程以执行任务,适用于需要并发处理的场景。
### 线程池实现示例
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <condition_variable>
#include <mutex>
#include <functional>
class ThreadPool {
public:
ThreadPool(size_t numThreads);
~ThreadPool();
// 添加任务到线程池
void enqueue(std::function<void()> task);
private:
// 工作线程函数
void worker();
std::vector<std::thread> workers; // 工作线程
std::queue<std::function<void()>> tasks; // 任务队列
std::mutex queueMutex; // 互斥锁
std::condition_variable condition; // 条件变量
bool stop; // 停止标志
};
// 线程池构造函数
ThreadPool::ThreadPool(size_t numThreads) : stop(false) {
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back( { worker(); });
}
}
// 线程池析构函数
ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queueMutex);
stop = true;
}
condition.notify_all(); // 唤醒所有线程
for (std::thread &worker : workers) {
worker.join(); // 等待所有线程结束
}
}
// 向任务队列添加任务
void ThreadPool::enqueue(std::function<void()> task) {
{
std::unique_lock<std::mutex> lock(queueMutex);
tasks.emplace(task); // 添加任务
}
condition.notify_one(); // 唤醒一个线程
}
// 工作线程函数
void ThreadPool::worker() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queueMutex);
condition.wait(lock, { return stop || !tasks.empty(); }); // 等待任务
if (stop && tasks.empty()) {
return; // 如果停止且没有任务,退出线程
}
task = std::move(tasks.front()); // 获取任务
tasks.pop(); // 移除任务
}
task(); // 执行任务
}
}
// 示例任务
void exampleTask(int id) {
std::cout << "Task " << id << " is running on thread " << std::this_thread::get_id() << std::endl;
}
int main() {
ThreadPool pool(4); // 创建一个线程池,包含4个线程
// 添加任务到线程池
for (int i = 0; i < 10; ++i) {
pool.enqueue( { exampleTask(i); });
}
// 稍等一下以确保所有任务完成
std::this_thread::sleep_for(std::chrono::seconds(2));
return 0;
}
### 代码说明
1. **ThreadPool 类**:
-`ThreadPool`构造函数:创建指定数量的工作线程。
-`~ThreadPool`析构函数:在对象销毁时停止所有线程并等待它们完成。
-`enqueue`方法:添加任务到任务队列。
-`worker`方法:工作线程从任务队列中获取任务并执行。
2. **示例任务**:
-`exampleTask`函数:用于演示任务执行,输出任务ID和线程ID。
3. **主函数**:
- 创建一个包含4个线程的线程池。
- 向线程池添加10个任务,并执行这些任务。
### 注意事项
- 线程池可以有效管理多个线程,避免频繁创建和销毁线程带来的开销。
- 在实际应用中,可能需要对任务的执行结果进行处理,或者添加更多的功能,如任务优先级等。
以上是一个简单的线程池实现示例,你可以根据需要进行扩展和优化。
页:
[1]