zoukankan      html  css  js  c++  java
  • 生产者消费者

    #include <pthread.h>  
    #include <semaphore.h>
    #include <unistd.h>  
    #include <stdio.h>
    #include<fcntl.h>
    #include <pthread.h>
    #include <errno.h>
    
    
    //文件锁,buffer锁,empty和full信号量
    sem_t file_mutex,buf_mutex,empty,full;
    
    int offset = 0;
    
    char buffer[256];
    
    void producer(int i){
    
        int k = 0;    
    
        while(k<8){
    
        sem_wait(&empty);
        sem_wait(&buf_mutex);
        sem_wait(&file_mutex);
        
        //从源文件读取
        int fd = open("./source.txt",O_RDWR);
        lseek(fd,offset,SEEK_SET);
        read(fd,buffer,1);
        printf("Producer %d is working!
    ",i);
        k++;
        offset++;
        
    
        sem_post(&file_mutex);
        sem_post(&buf_mutex);
        sem_post(&full);
        usleep(10);
    
        }
        
    
    
    
    }
    
    
    void consumer(int i){
    
        int k = 0;
    
        while(k<5){
    
        sem_wait(&full);
        sem_wait(&buf_mutex);
        
        //从buffer中取数据,打印
        printf("Consumer %d printfs %s
    ",i,buffer);
        k++;
        
        
        sem_post(&buf_mutex);
        sem_post(&empty);
        usleep(10);
    
    
        }
    
    }
    
    int main(){
    
        sem_init(&file_mutex, 0, 1);
        sem_init(&buf_mutex, 0, 1);
        sem_init(&full, 0, 0);
        sem_init(&empty, 0, 5);
    
        pthread_t pro1,pro2,pro3,con1,con2,con3,con4;
    
        
        //3个生产者,4个消费者。
        pthread_create(&pro1,NULL,(void*)producer,1);
        pthread_create(&pro2,NULL,(void*)producer,2);
        pthread_create(&pro3,NULL,(void*)producer,3);
        pthread_create(&con1,NULL,(void*)consumer,1);
        pthread_create(&con2,NULL,(void*)consumer,2);
        pthread_create(&con3,NULL,(void*)consumer,3);
        pthread_create(&con4,NULL,(void*)consumer,4);
    
    
        pthread_join(pro1,NULL);
        pthread_join(pro2,NULL);
        pthread_join(pro3,NULL);
        pthread_join(con1,NULL);
        pthread_join(con2,NULL);
        pthread_join(con3,NULL);
        pthread_join(con4,NULL);
    
    
    
    
    
    }
  • 相关阅读:
    F#学习开篇(一)
    F#学习(二)
    认识“闭包”
    Silverlight显示控件换行的几种方式
    关于P问题、NP问题、NPC问题
    LINQ&EF任我行(二)LinQ to Object
    WPF中资源的引用方法
    Linq to EF 与Linq to Object 使用心得
    C#中如何用拼音模糊匹配汉字的首字母
    WPF获取应用程序路径方法,获取程序运行路径方法
  • 原文地址:https://www.cnblogs.com/wzben/p/5418702.html
Copyright © 2011-2022 走看看