• 条件变量实现生产者消费者问题


    生产者消费者是典型的线程同步问题,生产者往共享区域中生产加入产品,消费者往共享区域中消费取出产品。

    生产者:若共享区域未满,则加入产品,并通知消费者;若共享区域已满,则等待消费者消费。

    消费者:若共享区域为空,则等待生产者生产;若共享区域未满,则消费并通知生产者。

    #include<stdio.h>
    #include<stdlib.h>
    #include<pthread.h>
    #include<unistd.h>
    
    const int TASK_SIZE = 100;
    
    typedef struct Task{
        int data;
        struct Task *next;
    }task;
    
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  //共享区域互斥锁
    pthread_cond_t notempty = PTHREAD_COND_INITIALIZER;  //任务非空条件变量
    pthread_cond_t notfull = PTHREAD_COND_INITIALIZER;  //任务满条件变量
    
     task *head = NULL;
     int task_num = 0;
    
     void *producer(void *arg)
     {
    
         while (1)
         {
            task *new = malloc(sizeof(task));
            new->data = rand() % 100;
    
            pthread_mutex_lock(&mutex);
            while(task_num == TASK_SIZE){
                pthread_cond_wait(&notfull, &mutex);
            }
            new->next = head;
            head = new;
            task_num++;
            printf("producer:%d\n", new->data);
            pthread_mutex_unlock(&mutex);
    
            pthread_cond_signal(&notempty);
    
            sleep(1);
         }
    }
    
    
    void* consumer(void* arg){
        while(1){
            pthread_mutex_lock(&mutex);
            while(head==NULL){  //while循环防止wait返回时发生虚假唤醒
                pthread_cond_wait(&notempty, &mutex);
            }
            task *old = head;
            head = head->next;
            task_num--;
            printf("consumer:%d\n", old->data);
            pthread_mutex_unlock(&mutex);
    
            pthread_cond_signal(&notfull);
    
            free(old);
    
            sleep(2);
        }
    
    }
    
    
    int main(){
    
        pthread_t pt, ct;
        
        pthread_mutex_init(&mutex, NULL);
    
        pthread_create(&pt, NULL, producer, NULL);
        pthread_create(&ct, NULL, consumer, NULL);
    
        pthread_join(pt, NULL);
        pthread_join(ct, NULL);
    
        pthread_mutex_destroy(&mutex);
        pthread_cond_destroy(&notempty);
        pthread_cond_destroy(&notfull);
    
        return 0;
    }
    

      

  • 相关阅读:
    dfa最小化,终于完成了。
    nfa转dfa,正式完成
    正则转nfa:完成
    正则转nfa:bug消除
    myeclipse集成jad反编译步骤
    CSS声明 列表样式 显示方式 鼠标形状
    CSS声明2 定位
    CSS声明1
    CSS基础知识简介
    lol简介/html
  • 原文地址:https://www.cnblogs.com/zyb993963526/p/16154322.html
Copyright © 2020-2023  润新知