C语言实现线程池例子

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define MAX_THREADS 4
#define MAX_TASKS 100

typedef struct {
    void (*function)(void *);
    void *argument;
} task_t;

task_t task_queue[MAX_TASKS];
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t queue_not_empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t queue_not_full = PTHREAD_COND_INITIALIZER;
int head = 0, tail = 0, count = 0;

void *worker(void *param) {
    while (1) {
        task_t task;
        pthread_mutex_lock(&queue_mutex);
        while (count == 0) {
            pthread_cond_wait(&queue_not_empty, &queue_mutex);
        }
        task = task_queue[head];
        head = (head + 1) % MAX_TASKS;
        count--;
        pthread_cond_signal(&queue_not_full);
        pthread_mutex_unlock(&queue_mutex);

        (*(task.function))(task.argument);
    }
    return NULL;
}

void submit_task(void (*function)(void *), void *argument) {
    pthread_mutex_lock(&queue_mutex);
    while (count == MAX_TASKS) {
        pthread_cond_wait(&queue_not_full, &queue_mutex);
    }
    task_queue[tail].function = function;
    task_queue[tail].argument = argument;
    tail = (tail + 1) % MAX_TASKS;
    count++;
    pthread_cond_signal(&queue_not_empty);
    pthread_mutex_unlock(&queue_mutex);
}

int main() {
    pthread_t threads[MAX_THREADS];

    for (int i = 0; i < MAX_THREADS; i++) {
        pthread_create(&threads[i], NULL, worker, NULL);
    }

    for (int i = 0; i < 10; i++) {
        int *arg = malloc(sizeof(*arg));
        *arg = i;
        submit_task(&printf, arg);
    }

    for (int i = 0; i < MAX_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值