如何实现线程池并用c/c++举例说明
时间: 2023-07-07 11:34:22 浏览: 104
C/C++中可以通过pthread库来实现线程池。下面是一个简单的C++线程池实现的代码示例:
```cpp
#include <iostream>
#include <pthread.h>
#include <queue>
using namespace std;
class ThreadPool {
public:
ThreadPool(int size) {
this->size = size;
threads = new pthread_t[size];
for (int i = 0; i < size; i++) {
pthread_create(&threads[i], NULL, worker, this);
}
}
void addTask(void (*task)(void*), void* arg) {
pthread_mutex_lock(&mutex);
tasks.push(make_pair(task, arg));
pthread_mutex_unlock(&mutex);
}
void waitAll() {
for (int i = 0; i < size; i++) {
pthread_join(threads[i], NULL);
}
}
private:
static void* worker(void* arg) {
ThreadPool* pool = static_cast<ThreadPool*>(arg);
while (true) {
pthread_mutex_lock(&pool->mutex);
if (pool->tasks.empty()) {
pthread_mutex_unlock(&pool->mutex);
break;
}
auto task = pool->tasks.front();
pool->tasks.pop();
pthread_mutex_unlock(&pool->mutex);
task.first(task.second);
}
return NULL;
}
int size;
pthread_t* threads;
queue<pair<void (*)(void*), void*>> tasks;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
};
void task(void* arg) {
int* num = static_cast<int*>(arg);
cout << "Task #" << *num << " is running." << endl;
delete num;
}
int main() {
ThreadPool pool(5);
for (int i = 0; i < 10; i++) {
int* num = new int(i);
pool.addTask(task, num);
}
pool.waitAll();
return 0;
}
```
上面的代码使用了pthread库来创建线程池,并通过addTask方法将任务添加到线程池的任务队列中。执行结果如下:
```
Task #0 is running.
Task #1 is running.
Task #2 is running.
Task #3 is running.
Task #4 is running.
Task #5 is running.
Task #6 is running.
Task #7 is running.
Task #8 is running.
Task #9 is running.
```
这里的任务只是简单地输出了一条信息,实际上可以根据需要编写自己的任务逻辑,利用线程池提高程序的执行效率和稳定性。
阅读全文