溫馨提示×

linux pthread_t線程池的設(shè)計與實現(xiàn)

小樊
83
2024-09-05 15:29:23
欄目: 智能運維

在Linux中,使用pthread_t實現(xiàn)線程池需要以下幾個步驟:

  1. 定義線程池結(jié)構(gòu)體:
#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. 線程池工作函數(shù):
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. 添加任務(wù)到線程池:
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的線程池就設(shè)計和實現(xiàn)完成了。你可以根據(jù)自己的需求調(diào)整線程池的大小、隊列大小等參數(shù)。

0