一个失败的生产者,消费者代码

本文详细解析了线程池的结构设计及其核心组件,着重阐述了主线程与工作线程之间的通信机制,通过实例代码展示了如何在多线程环境下高效处理并发任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是本人前不久刚挖出来的,热呼呼的还冒着气。

谁能发现坑在哪


背景:

thread_main 函数:负责accept socket ,然后分发给worker thread。

thread_worker函数:负责消耗掉main thread 传递过来的线程。

关系图:

234535_Ze1A_1429274.jpg


结构体设计:

struct thread_pool {
    pthread_mutex_t mutex;
    pthread_cond_t  cond;

    pthread_t       tids[MAX_THREADS];
    int             connfd;
    int             ready;

    void (*process)(int s);
};


thread_main 函数实现:

static void thread_main(struct thread_pool *pool, int s) {
    int connfd;

    for (;;) {
        /*get client sock*/
        connfd = accept(s, NULL, NULL);
        fprintf(stderr, "current sock = %d\n", connfd);

        if (connfd == -1) {
            perror("accept");
            break;
        }

        pthread_mutex_lock(&pool->mutex);

        printf("main: ready = %d\n", pool->ready);
        while (pool->ready == 1) {
            pthread_cond_wait(&pool->cond, &pool->mutex);
        }
        pool->connfd = connfd;
        pool->ready  = 1;
        pthread_cond_signal(&pool->cond);

        pthread_mutex_unlock(&pool->mutex);
    }
}


thread_worker 函数实现:

static void *thread_worker(void *arg) {

    struct thread_pool *p = (struct thread_pool *)arg;

    int connfd = -1;
    for (;;) {
        pthread_mutex_lock(&p->mutex);

        while (p->ready == 0) {
            pthread_cond_wait(&p->cond, &p->mutex);
        }
        connfd   = p->connfd;
        p->ready = 0;

        printf("ready = %d\n", p->ready);
        pthread_mutex_unlock(&p->mutex);

        p->process(connfd);
    }
    return (void *)0;
}


转载于:https://my.oschina.net/guonaihong/blog/296044

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值