生產者-消費者問題是作業系統的經典問題,需求是這樣的:在系統中建立乙個共享記憶體區域,記憶體區有長度為1的浮點陣列,兩個程序分別對共享記憶體區進行操作,程序a複雜迴圈向共享記憶體區域寫入資料,b複雜讀取由程序a產生的資料。
為了更好的利用訊號量,觀察效果,a和b程序沒有親緣關係。**如下
/*程序a,負責傳送資料*/
#include #include#include #include #include #include #include #include #include#include #includetypedef struct
shame_buf;//共享記憶體資料型別
typedef union semun
semctl_union;//訊號量控制時所需要傳遞的引數型別
int main(void)
if((id_sem=semget(key,2,ipc_creat|ipc_excl|0666))==-1)//建立訊號量集合包含兩個訊號量
if((id_sem=semget(key,2,0))<0)//獲取已經存在的訊號量集合
}printf("id_sem=%d\n",id_sem);//列印訊號量集合的描述符號
semctl_arg.val=0;//初始值為0
/*必須清除*/
memset(&semop_buf,0x00,sizeof(struct sembuf));
memset(&semop_buf2,0x00,sizeof(struct sembuf));
semop_buf.sem_num=0;//第乙個訊號
semop_buf.sem_op=1;//設定訊號量操作 v
semop_buf2.sem_num=1;//訊號集的第二個訊號
semop_buf2.sem_op=-1;//設定訊號量操作 p
if(semctl(id_sem,0,setval,semctl_arg)<0)//設定訊號量1初始值0
if(semctl(id_sem,1,setval,semctl_arg)<0)//設定訊號量2初始值0
if((id_shm=shmget(key,sizeof(shame_buf),ipc_creat|0666))<0)//建立共享記憶體
if((shm_buf=shmat(id_shm,null,0))==(void *)-1)//對映共享記憶體到本地
printf("id_shm=%d\n",id_shm);//輸出共享記憶體描述符號
shm_buf->buff_dat=0;
while(1)
if(semop(id_sem,&semop_buf2,1)==-1)
if(i==10)
}shmctl(id_shm,ipc_rmid,0);//刪除共享記憶體
semctl(id_sem,ipc_rmid,0);//刪除訊號量
return 0;
}
程序a負責向共享記憶體區寫入資料,寫完後,程序a阻塞,程序b開始列印,程序b列印完成後,a會繼續寫入,就這樣一直重複十次.當初因為忘記了清零/*程序b,負責列印資料*/
#include #include #include #include #include #include #include #include#include #includetypedef struct
shame_buf;//共享記憶體資料型別
typedef union semun
semctl_union;//訊號量控制時所需要傳遞的引數型別
int main(void)
while(1)
printf("the num %d data is %lf\n",i,shm_buf->buff_dat);//讀共享記憶體發過來的數
i++;//計數
if(semop(id_sem,&semop_buf2,1)==-1)//執行v操作,該程序此刻被阻塞,直到傳送程序
if(i==10)
}shmctl(id_shm,ipc_rmid,0);//刪除共享記憶體
semctl(id_sem,ipc_rmid,0);//刪除訊號量
return 0;
}
出現了一些不愉快,參考memset(&semop_buf,0x00,sizeof(struct sembuf));
memset(&semop_buf2,0x00,sizeof(struct sembuf));
非常感謝。前面幾天一直學習linux作業系統的程序間通訊,通過消費者生產者問題綜合鍛鍊了下自己的能力,感覺有幫助,**自己寫,但是感覺收穫很多。
生產者 消費者問題實現
include include include include include include define need p 2 生產者程序數 define need c 2 消費者程序數 define works p 10 每個生產者程序執行的次數 define works c 10 每個消費者程序...
程序模擬生產者 消費者問題
這裡我只是簡單實現了這個經典問題的思路與想打,並且書寫的程式也是能正確的執行出合理的答案,希望今後還可以改進程式使之更加完善 思路描述 1.生產者程序 產生乙個資料,當要送入緩衝區的時候,要檢查緩衝區是否已滿,若未滿,則可將資料送入緩衝區,並通知消費者程序,否則等待 2.對於消費者程序 當它去取資料...
生產者消費者問題
public class producer consumer class godown public godown int num public synchronized void produce int n catch interruptedexception e curr num n syste...