C++实现线程池代码
时间: 2023-02-12 21:28:53 浏览: 115
C++实现线程池的简单方法示例
以下是一个简单的C语言实现的线程池代码:
```
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_THREADS 10
#define MAX_QUEUE_SIZE 100
typedef struct {
void (*function)(void *);
void *data;
} threadpool_task_t;
typedef struct {
pthread_mutex_t lock;
pthread_cond_t notify;
pthread_t *threads;
threadpool_task_t *queue;
int thread_count;
int queue_size;
int head;
int tail;
int count;
int shutdown;
int started;
} threadpool_t;
threadpool_t *threadpool_create(int thread_count, int queue_size, int flags) {
threadpool_t *pool;
int i;
if (thread_count <= 0 || thread_count > MAX_THREADS || queue_size <= 0 || queue_size > MAX_QUEUE_SIZE) {
return NULL;
}
if ((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL) {
return NULL;
}
pool->thread_count = 0;
pool->queue_size = queue_size;
pool->head = pool->tail = pool->count = 0;
pool->shutdown = pool->started = 0;
pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_count);
pool->queue = (threadpool_task_t *)malloc(sizeof(threadpool_task_t) * queue_size);
if ((pthread_mutex_init(&(pool->lock), NULL) != 0) ||
(pthread_cond_init(&(pool->notify), NULL) != 0) ||
(pool->threads == NULL) ||
(pool->queue == NULL)) {
return NULL;
}
for (i = 0; i < thread_count; i++) {
if (pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void*)pool) != 0) {
threadpool_destroy(pool, 0);
return NULL;
}
pool->thread_count++;
pool->started++;
}
return pool;
}
int threadpool_add(threadpool_t *pool, void (*function)(void *), void *data) {
int next;
if (pool == NULL || function == NULL) {
return -1;
}
if (pthread_mutex_lock(&(pool->lock)) != 0) {
return -1;
}
next = pool->tail + 1;
next = (next == pool->queue_size) ? 0 : next;
if (pool->count == pool->queue_size) {
pthread_mutex_unlock(&(pool->lock));
return
阅读全文