C++实现线程池代码
时间: 2023-02-12 21:24:01 浏览: 111
C++实现线程池
4星 · 用户满意度95%
以下是一份简单的C语言实现的线程池代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_THREADS 10
#define MAX_QUEUE_SIZE 100
typedef struct {
void *(*function)(void *);
void *arg;
} 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)) {
goto error;
}
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;
error:
if (pool) {
threadpool_free(pool);
}
return NULL;
}
int threadpool_add(threadpool_t *pool, void *(*function)(void *), void *argument, int flags)
{
int err = 0;
int next;
if (pool == NULL || function == NULL) {
return threadpool_invalid;
}
if (pthread_mutex_lock(&(pool->lock)) != 0) {
return threadpool_lock_failure;
}
next = (pool->tail + 1) %
阅读全文