温馨提示×

linux pthread_t线程池的设计与实现

小樊
83
2024-09-05 15:29:23
栏目: 智能运维

在Linux中,使用pthread_t实现线程池需要以下几个步骤:

  1. 定义线程池结构体:
#include <pthread.h>
#include <stdbool.h>

typedef struct Task {
    void (*func)(void *);
    void *arg;
    struct Task *next;
} Task;

typedef struct ThreadPool {
    pthread_mutex_t lock;
    pthread_cond_t cond;
    pthread_t *threads;
    Task *head;
    Task *tail;
    int thread_count;
    int queue_size;
    bool shutdown;
} ThreadPool;
  1. 初始化线程池:
ThreadPool *threadpool_init(int thread_count, int queue_size) {
    ThreadPool *pool = (ThreadPool *)malloc(sizeof(ThreadPool));
    pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_count);
    pool->head = NULL;
    pool->tail = NULL;
    pool->thread_count = thread_count;
    pool->queue_size = queue_size;
    pool->shutdown = false;

    pthread_mutex_init(&pool->lock, NULL);
    pthread_cond_init(&pool->cond, NULL);

    for (int i = 0; i< thread_count; i++) {
        pthread_create(&pool->threads[i], NULL, threadpool_worker, (void *)pool);
    }

    return pool;
}
  1. 线程池工作函数:
void *threadpool_worker(void *arg) {
    ThreadPool *pool = (ThreadPool *)arg;
    while (1) {
        pthread_mutex_lock(&pool->lock);
        while (pool->head == NULL && !pool->shutdown) {
            pthread_cond_wait(&pool->cond, &pool->lock);
        }

        if (pool->shutdown) {
            pthread_mutex_unlock(&pool->lock);
            pthread_exit(NULL);
        }

        Task *task = pool->head;
        pool->head = task->next;
        if (pool->head == NULL) {
            pool->tail = NULL;
        }
        pthread_mutex_unlock(&pool->lock);

        task->func(task->arg);
        free(task);
    }
}
  1. 添加任务到线程池:
void threadpool_add_task(ThreadPool *pool, void (*func)(void *), void *arg) {
    Task *task = (Task *)malloc(sizeof(Task));
    task->func = func;
    task->arg = arg;
    task->next = NULL;

    pthread_mutex_lock(&pool->lock);
    if (pool->tail) {
        pool->tail->next = task;
    } else {
        pool->head = task;
    }
    pool->tail = task;
    pthread_cond_signal(&pool->cond);
    pthread_mutex_unlock(&pool->lock);
}
  1. 销毁线程池:
void threadpool_destroy(ThreadPool *pool) {
    pthread_mutex_lock(&pool->lock);
    pool->shutdown = true;
    pthread_cond_broadcast(&pool->cond);
    pthread_mutex_unlock(&pool->lock);

    for (int i = 0; i< pool->thread_count; i++) {
        pthread_join(pool->threads[i], NULL);
    }

    while (pool->head) {
        Task *task = pool->head;
        pool->head = task->next;
        free(task);
    }

    pthread_mutex_destroy(&pool->lock);
    pthread_cond_destroy(&pool->cond);
    free(pool->threads);
    free(pool);
}

这样,一个基于pthread_t的线程池就设计和实现完成了。你可以根据自己的需求调整线程池的大小、队列大小等参数。

0