线程池完整实例代码 vc
时间: 2023-10-17 09:24:53 浏览: 50
以下是一个基本的线程池实现代码示例,使用C++和Windows API实现:
```c++
#include <iostream>
#include <queue>
#include <vector>
#include <Windows.h>
#define MAX_THREADS 4 // 线程池中的最大线程数
using namespace std;
// 线程池类
class ThreadPool {
public:
ThreadPool() {
InitializeCriticalSection(&m_cs); // 初始化临界区
m_hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); // 创建事件对象
}
~ThreadPool() {
DeleteCriticalSection(&m_cs); // 删除临界区
CloseHandle(m_hEvent); // 关闭事件对象
for (int i = 0; i < m_vecThreads.size(); i++) {
CloseHandle(m_vecThreads[i]); // 关闭线程句柄
}
}
// 添加任务
void AddTask(LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter) {
EnterCriticalSection(&m_cs); // 进入临界区
m_queueTasks.push(make_pair(lpStartAddress, lpParameter)); // 将任务添加到队列中
SetEvent(m_hEvent); // 设置事件对象
LeaveCriticalSection(&m_cs); // 离开临界区
}
// 开始线程池
void Start() {
for (int i = 0; i < MAX_THREADS; i++) {
HANDLE hThread = CreateThread(NULL, 0, ThreadPool::ThreadProc, this, 0, NULL); // 创建线程
m_vecThreads.push_back(hThread); // 将线程句柄添加到向量中
}
}
// 等待所有任务执行完毕
void WaitAll() {
WaitForMultipleObjects(m_vecThreads.size(), &m_vecThreads[0], TRUE, INFINITE);
}
private:
// 线程函数
static DWORD WINAPI ThreadProc(LPVOID lpParameter) {
ThreadPool* pThreadPool = (ThreadPool*)lpParameter;
while (true) {
WaitForSingleObject(pThreadPool->m_hEvent, INFINITE); // 等待事件对象
EnterCriticalSection(&pThreadPool->m_cs); // 进入临界区
if (pThreadPool->m_queueTasks.empty()) { // 队列为空,跳出循环
LeaveCriticalSection(&pThreadPool->m_cs); // 离开临界区
break;
}
auto task = pThreadPool->m_queueTasks.front(); // 取出队首任务
pThreadPool->m_queueTasks.pop(); // 弹出队首任务
LeaveCriticalSection(&pThreadPool->m_cs); // 离开临界区
task.first(task.second); // 执行任务
}
return 0;
}
private:
CRITICAL_SECTION m_cs; // 临界区
HANDLE m_hEvent; // 事件对象
queue<pair<LPTHREAD_START_ROUTINE, LPVOID>> m_queueTasks; // 任务队列
vector<HANDLE> m_vecThreads; // 线程句柄向量
};
// 测试函数
DWORD WINAPI TestThread(LPVOID lpParameter) {
int n = *((int*)lpParameter);
cout << "Thread " << n << " start" << endl;
Sleep(1000); // 模拟任务执行
cout << "Thread " << n << " end" << endl;
return 0;
}
int main() {
ThreadPool threadPool;
threadPool.Start();
for (int i = 0; i < 10; i++) {
threadPool.AddTask(TestThread, &i);
}
threadPool.WaitAll();
return 0;
}
```
以上是一个简单的线程池实现代码示例,其中使用了Windows API的临界区、事件对象和线程函数等功能。在测试函数中,模拟了一个耗时的任务,并将其添加到线程池中,最终等待所有任务执行完毕后结束程序。