可以写一个c++线程池的实例吗
时间: 2023-04-08 10:00:46 浏览: 184
可以,我可以为您提供一个简单的C线程池实例:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define THREAD_POOL_SIZE 10
typedef struct {
void (*function)(void *);
void *argument;
} thread_task;
pthread_mutex_t mutex;
pthread_cond_t condition;
thread_task *task_queue;
int task_queue_size = 0;
int task_queue_capacity = 0;
int head = 0;
int tail = 0;
int thread_count = 0;
int shutdown = 0;
void thread_pool_init() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&condition, NULL);
task_queue_capacity = THREAD_POOL_SIZE;
task_queue = (thread_task *)malloc(sizeof(thread_task) * task_queue_capacity);
for (int i = 0; i < THREAD_POOL_SIZE; i++) {
pthread_t thread;
pthread_create(&thread, NULL, thread_pool_worker, NULL);
pthread_detach(thread);
thread_count++;
}
}
void thread_pool_shutdown() {
pthread_mutex_lock(&mutex);
shutdown = 1;
pthread_cond_broadcast(&condition);
pthread_mutex_unlock(&mutex);
}
void thread_pool_add_task(void (*function)(void *), void *argument) {
pthread_mutex_lock(&mutex);
if (task_queue_size == task_queue_capacity) {
task_queue_capacity *= 2;
task_queue = (thread_task *)realloc(task_queue, sizeof(thread_task) * task_queue_capacity);
}
task_queue[tail].function = function;
task_queue[tail].argument = argument;
tail = (tail + 1) % task_queue_capacity;
task_queue_size++;
pthread_cond_signal(&condition);
pthread_mutex_unlock(&mutex);
}
void *thread_pool_worker(void *arg) {
while (1) {
pthread_mutex_lock(&mutex);
while (task_queue_size == 0 && !shutdown) {
pthread_cond_wait(&condition, &mutex);
}
if (shutdown) {
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void (*function)(void *) = task_queue[head].function;
void *argument = task_queue[head].argument;
head = (head + 1) % task_queue_capacity;
task_queue_size--;
pthread_mutex_unlock(&mutex);
function(argument);
}
}
void print_message(void *arg) {
char *message = (char *)arg;
printf("%s\n", message);
}
int main() {
thread_pool_init();
thread_pool_add_task(print_message, "Hello, world!");
thread_pool_add_task(print_message, "This is a test.");
thread_pool_add_task(print_message, "Goodbye!");
sleep(1);
thread_pool_shutdown();
return 0;
}
```
这是一个简单的线程池实现,使用了互斥锁和条件变量来实现任务队列的同步。线程池初始化时创建了一定数量的线程,当有任务加入队列时,唤醒一个等待的线程来执行任务。当线程池关闭时,向所有等待的线程发送关闭信号,线程退出。
阅读全文