一、基础概念
pthread_create
用于创建新线程,pthread_join
用于等待线程结束等。二、优势
三、类型
四、应用场景
五、可能遇到的问题及解决方法
以下是一个简单的Linux C++ 固定大小线程池示例代码:
#include <iostream>
#include <vector>
#include <queue>
#include <pthread.h>
#include <unistd.h>
// 任务结构体
struct Task {
void (*function)(void*);
void* argument;
};
// 线程池类
class ThreadPool {
private:
std::queue<Task> taskQueue;
pthread_mutex_t queueMutex;
pthread_cond_t condition;
bool stop;
std::vector<pthread_t> threads;
int threadCount;
public:
ThreadPool(int numThreads);
~ThreadPool();
void addTask(void (*function)(void*), void* argument);
};
ThreadPool::ThreadPool(int numThreads) {
threadCount = numThreads;
stop = false;
pthread_mutex_init(&queueMutex, NULL);
pthread_cond_init(&condition, NULL);
for (int i = 0; i < numThreads; ++i) {
pthread_t thread;
pthread_create(&thread, NULL, [](void* arg) {
ThreadPool* pool = (ThreadPool*)arg;
while (true) {
Task task;
pthread_mutex_lock(&pool->queueMutex);
while (pool->taskQueue.empty() &&!pool->stop) {
pthread_cond_wait(&pool->condition, &pool->queueMutex);
}
if (pool->stop && pool->taskQueue.empty()) {
pthread_mutex_unlock(&pool->queueMutex);
break;
}
task = pool->taskQueue.front();
pool->taskQueue.pop();
pthread_mutex_unlock(&pool->queueMutex);
task.function(task.argument);
}
}, this);
threads.push_back(thread);
}
}
ThreadPool::~ThreadPool() {
stop = true;
pthread_cond_broadcast(&condition);
for (pthread_t thread : threads) {
pthread_join(thread, NULL);
}
pthread_mutex_destroy(&queueMutex);
pthread_cond_destroy(&condition);
}
void ThreadPool::addTask(void (*function)(void*), void* argument) {
Task task;
task.function = function;
task.argument = argument;
pthread_mutex_lock(&queueMutex);
taskQueue.push(task);
pthread_cond_signal(&condition);
pthread_mutex_unlock(&queueMutex);
}
// 示例任务函数
void exampleTask(void* num) {
int* n = (int*)num;
std::cout << "Task executed by thread " << pthread_self() << " with number " << *n << std::endl;
sleep(1);
}
int main() {
ThreadPool pool(3);
for (int i = 0; i < 5; ++i) {
int* num = new int(i);
pool.addTask(exampleTask, num);
}
sleep(10);
return 0;
}
在这个示例中:
Task
结构体来表示任务,包含任务函数指针和参数。ThreadPool
类管理线程池的创建、任务添加和销毁等操作。main
函数中创建了一个包含3个线程的线程池,并添加了5个任务到线程池中执行。领取专属 10元无门槛券
手把手带您无忧上云