基於訊號量機制的進程同步問題類比程式

來源:互聯網
上載者:User
背景:在多任務系統中,進程之間的相互影響成為必須解決的重要問題,由於共用資源爭搶(間接制約)和進程之間的固有協作關係(直接制約),導致進程之間存在相互制約關係。1965年荷蘭學者Dijkstra提出的訊號量機制是用於解決進程間同步問題的一種重要機制。問題描述:在父親、女兒和兒子面前有一個放置水果的盤子plate,盤子最多可以放6個水果。父親隨機地向盤子裡放入水果,可能是蘋果也可能是桔子。女兒和兒子從盤 子中拿水果吃,但是女兒只吃桔子orange,兒子只吃蘋果apple,並且每次只能有一個人對盤子訪問(放水果或者拿水果)。這是作業系統課上的第三次作業吧,晚上做了一下,只是個類比程式,還不夠完善。
#define RUNNING     0  #define READY       1  #define BLOCK    2#define FATHER9#define SON8#define DAUGHTER7 #include <stdio.h>#include <time.h>#include <stdlib.h>typedef struct PCB{int pid;//進程的標識號int pstatus;//進程的狀態struct PCB * next;//指向下一個進程的指標}PCB;/* 訊號量定義 */typedef struct semaphore {int value;//初始為0int id;//0表示orange,1表示apple,2表示空PCB *bqhead;}semaphore;/* 阻塞函數 */void block(PCB *process){/* 將進程阻塞 *//* 將函數狀態修改為阻塞態,保證main函數調度的時候不會調度阻塞狀態的函數運行 */process->pstatus=2;//阻塞態if(process->pid==9)printf("Father block!\n");if(process->pid==8)printf("Son block!\n");if(process->pid==7)printf("Daughter block!\n");}/* 喚醒函數 */void wakeup(PCB *process){/* 喚醒進程  *//* 將函數狀態修改為就緒態,main函數調度的時候會調度就緒狀態的函數運行 */process->pstatus=1;//就緒態if(process->pid==9)printf("Father wakeup!\n");if(process->pid==8)printf("Son wakeup!\n");if(process->pid==7)printf("Daughter wakeup!\n");}/* wait操作 */void wait(semaphore *s){s->value--;if (s->value<0) {block(s->bqhead);}}/* signal操作 */void signal(semaphore *s){s->value++;if (s->value<=0) {wakeup(s->bqhead);}}int main(){int count=0;semaphore *s;PCB *pcb;s=(semaphore *)malloc(sizeof(semaphore));s->value=0;s->id=2;pcb=(PCB *)malloc(sizeof(PCB));pcb->pstatus=1;//初始化狀態為就緒態srand((unsigned)time(NULL));//產生一個隨機種子while(count!=20){int i = rand() % 3+7 ;//在7-9中隨機產生一個數,即從pcb->pid=i;if(s->value<=6 && pcb->pstatus!=2){if(pcb->pid==9 )//父親放水果{s->id=rand()%2;//產生0或1表示放入的水果為橘子或蘋果signal(s);if(s->id==1)printf("Father put an Apple!\n");else if(s->id==0)printf("Father put an Orange!\n");}}if (s->value>0 && pcb->pstatus!=2){if(s->id==1 && pcb->pid==8)//蘋果{wait(s);printf("Son pick an Apple!\n");}else if(s->id==0&&pcb->pid==8)//橘子{printf("Son don't like Orange\n");}else if(s->id==0&&pcb->pid==9)//蘋果{wait(s);printf("Daughter pick an Orange!\n");}else if(s->id==1&&pcb->pid==9)//橘子printf("Daughter don't like Apple!\n");}else{int k=rand() % 2+1;//1-2switch(k){case 1:block(pcb);break;case 2:wakeup(pcb);break;}}count++;//統計迴圈次數}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.