c用信号量(Semaphore)实现消费者生产者同步

来源:互联网 发布:windows 10版本 编辑:程序博客网 时间:2024/05/19 20:00
// 前面一篇博客的生产者-消费者的例子是基于链表的,其空间可以动态分配,现在基于固定大小的环形队列重写这个程序:#include <stdlib.h>#include <pthread.h>#include <stdio.h>#include <semaphore.h>#define NUM 5int queue[NUM];/** * semaphore变量的类型为sem_t,sem_init()初始化一个semaphore变量, * value参数表示可用资源的数量,pshared参数为0表示信号量用于同一进程的线程间同步 */sem_t blank_number, product_number;void *producer(void *arg){    static int p = 0;    while(1){        // 调用sem_wait()可以获得资源,使semaphore的值减1,如果调用sem_wait()时semaphore的值已经是0,则挂起等待。        // 如果不希望挂起等待,可以调用sem_trywait()。        // 这里使得blank_number的值减1,初始值是5        sem_wait(&blank_number);        queue[p] = rand()%1000;        printf("Produce %d\n", queue[p]);        p = (p+1)%NUM;        sleep(rand()%5);        // 调用sem_post()可以释放资源,使semaphore的值加1,同时唤醒挂起等待的线程。        // 使得product_number值加1,初始值是0        sem_post(&product_number);    }}void *consumer(void *arg){    static int c = 0;    while(1){        // 使得product_number值加1,初始值是0        sem_wait(&product_number);        printf("Consume %d\n", queue[c]);        c = (c+1)%NUM;        sleep(rand()%5);        // 这里使得blank_number的值减1,初始值是5        sem_post(&blank_number);    }}int main(int argc, char *argv[]){    //刷新 console cdt下的配置,其他可以忽略    setbuf(stdout,NULL);    pthread_t pid, cid;    sem_init(&blank_number, 0, NUM);    sem_init(&product_number, 0, 0);    pthread_create(&pid, NULL, producer, NULL);    pthread_create(&cid, NULL, consumer, NULL);    pthread_join(pid, NULL);    pthread_join(cid, NULL);    sem_destroy(&blank_number);    sem_destroy(&product_number);    return 0;}

这篇和上一篇博客的例子给出一个重要的提示:用Condition Variable可以实现Semaphore。有时间用Condition Variable实现Semaphore,然后用自己实现的Semaphore重写本节的程序。

阅读全文
0 0
原创粉丝点击