互斥锁,条件变量的多生产者,单消费者简单…

作者在 2010-07-30 19:48:44 发布以下内容
//2010-01-19 yaojianming 摘自unix网络编程2
// 编译:g++ luts.cpp -o luts -lpthread

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

#define MAXNITEMS 100000
#define MAXNTHREADS 10

int nitems = MAXNITEMS;
int buff[MAXNITEMS];

struct val {
    pthread_mutex_t mutex;
    int nput;
    int nval;
} put = {
    PTHREAD_MUTEX_INITIALIZER, 0, 0
};

struct mutex_cond {
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    int nready;
} nready = {
    PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0
};

void* produce(void* arg)
{
    while(1) {
        pthread_mutex_lock(&put.mutex);
        if (put.nput >= nitems) {
            pthread_mutex_unlock(&put.mutex);
            return NULL;
        }
        buff[put.nput] = put.nval;
        put.nput++;
        put.nval++;
        pthread_mutex_unlock(&put.mutex);
        
        int dosignal;
        pthread_mutex_lock(&nready.mutex);
        dosignal = (nready.nready == 0);
        nready.nready++;
        pthread_mutex_unlock(&nready.mutex);
        
        if (dosignal)
            pthread_cond_signal(&nready.cond);
        
        *((int*)arg) += 1;
    }
}

void* consume(void* arg)
{
    for(int i=0; i<nitems; ++i) {
        pthread_mutex_lock(&nready.mutex);
        while(nready.nready == 0)
            pthread_cond_wait(&nready.cond, &nready.mutex);
        nready.nready--;
        pthread_mutex_unlock(&nready.mutex);
        
        if(buff[i] != i)
            printf("buff[%d] = %d\n", i, buff[i]);
    }
}

int main()
{
    int nthreads = MAXNTHREADS;
    int count[MAXNTHREADS];
    pthread_t tid_produce[MAXNTHREADS];
    pthread_t tid_consume;
    
    for(int i=0; i<nthreads; ++i) {
        count[i] = 0;
        pthread_create(&tid_produce[i], NULL, produce, &count[i]);
    }
    pthread_create(&tid_consume, NULL, consume, NULL);
    
    for(int i=0; i<nthreads; ++i) {
        pthread_join(tid_produce[i], NULL);
        printf("count[%d] = %d\n", i, count[i]);
    }
    printf("produce success\n");
    pthread_join(tid_consume, NULL);
    printf("consume success\n");
    
    return 0;
}

技术 | 阅读 2353 次
文章评论,共0条
游客请输入验证码
浏览1970272次