linux c pv 實現生產者消費者模型

來源:互聯網
上載者:User

//訊號量---線程間通訊//“生產者消費者” 問題#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<semaphore.h>#include<pthread.h>#definemsleep(x)usleep(x*1000)#define PRODUCT_SPEED3//生產速度#define CONSUM_SPEED1//消費速度#define INIT_NUM3//倉庫原有產品數#defineTOTAL_NUM10//倉庫容量sem_t p_sem, c_sem, sh_sem;int num=INIT_NUM;void product(void)//生產產品{sleep(PRODUCT_SPEED);}int add_to_lib()//添加產品到倉庫{num++;//倉庫中的產品增加一個msleep(500);return num;}void consum()//消費{sleep(CONSUM_SPEED);}int sub_from_lib()//從倉庫中取出產品{num--; //倉庫中的產品數量減一msleep(500);return num;}void *productor(void *arg)//生產者線程{while(1){sem_wait(&p_sem);//生產訊號量減一product();// 生產延時sem_wait(&sh_sem);//這個訊號量是用來互斥的printf("push into! tatol_num=%d\n",add_to_lib());sem_post(&sh_sem);sem_post(&c_sem);  //消費訊號量加一}}void *consumer(void *arg)//消費者線程{while(1){sem_wait(&c_sem); //消費者訊號量減一sem_wait(&sh_sem);printf("pop out! tatol_num=%d\n",sub_from_lib());sem_post(&sh_sem);sem_post(&p_sem);//生產者訊號量加一consum();//消費延時}}int main(){pthread_t tid1,tid2;sem_init(&p_sem,0,TOTAL_NUM-INIT_NUM);sem_init(&c_sem,0,INIT_NUM);sem_init(&sh_sem,0,1);pthread_create(&tid1,NULL,productor,NULL);pthread_create(&tid2,NULL,consumer,NULL);pthread_join(tid1,NULL);pthread_join(tid2,NULL);return 0;}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.