c 线程池的例子
线程池是一种用于管理线程的机制,可以避免频繁地创建和销毁线程,从而提高应用程序的性能。下面是一个使用C语言实现线程池的简单示例:
```c
include <>
include <>
include <>
include <>
define MAX_THREADS 5
define MAX_TASKS 10
typedef struct task {
    int id;
    int data;
} task;
typedef struct thread_pool {
    pthread_t threads[MAX_THREADS];
    task tasks[MAX_TASKS];
    int task_count;
    int thread_count;
    bool shutdown;
} thread_pool;
void worker(void arg) {
    thread_pool pool = (thread_pool )arg;
    while (1) {
        pthread_mutex_lock(&pool->mutex);
        while (pool->task_count == 0 && !pool->shutdown) {
            pthread_cond_wait(&pool->cond, &pool->mutex);
        }
        if (pool->shutdown && pool->task_count == 0) {
            pthread_mutex_unlock(&pool->mutex);
            pthread_exit(NULL);exited
        }
        task task = &pool->tasks[pool->task_count - 1];
        pool->task_count--;
        pthread_mutex_unlock(&pool->mutex);
        printf("Thread %ld is processing task %d with data %d\n", pthread_self(), task->id, task->data);
        free(task);
    }
}
void init_thread_pool(thread_pool pool) {
    pthread_mutex_init(&pool->mutex, NULL);
    pthread_cond_init(&pool->cond, NULL);
    pool->task_count = 0;
    pool->thread_count = 0;
    pool->shutdown = false;
}
void destroy_thread_pool(thread_pool pool) {
    pthread_mutex_destroy(&pool->mutex);
    pthread_cond_destroy(&pool->cond);
}
void add_task(thread_pool pool, int id, int data) {
    pthread_mutex_lock(&pool->mutex);
    if (pool->task_count < MAX_TASKS) {
        task task = (task )malloc(sizeof(task));
        task->id = id;
        task->data = data;
        pool->tasks[pool->task_count++] = task;
        pthread_cond_signal(&pool->cond); // notify any waiting threads that a new task is available

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。