PV操作哲學(xué)家問題和生產(chǎn)者-消費(fèi)者問題剖析_第1頁
PV操作哲學(xué)家問題和生產(chǎn)者-消費(fèi)者問題剖析_第2頁
PV操作哲學(xué)家問題和生產(chǎn)者-消費(fèi)者問題剖析_第3頁
PV操作哲學(xué)家問題和生產(chǎn)者-消費(fèi)者問題剖析_第4頁
PV操作哲學(xué)家問題和生產(chǎn)者-消費(fèi)者問題剖析_第5頁
已閱讀5頁,還剩5頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、PV操作(哲學(xué)家問題)給每個(gè)哲學(xué)家編號(hào),規(guī)定奇數(shù)號(hào)的哲學(xué)家先拿他的左筷子,然后再去拿他的右筷子;而偶 數(shù)號(hào)的哲學(xué)家則相反。這樣總可以保證至少有一個(gè)哲學(xué)家可以進(jìn)餐。include include include processhinclude include using namespace std;DWORD WINAPI philosopher(LPVOID IpParameter);void thinking(int):void eating(int);void waiting(int);void print(int ,const char *);全局變量CRITICAL_SECTION c

2、rout;/這個(gè)變量用來保證輸出時(shí)不會(huì)竟7CRITICAL_SECTION fork5;/定義五個(gè)臨界變量,代表五更筷J: int main(int argc, char *argv)HANDLE hthread5;int i;int arg5;int count = 5;long a=0;unsigned long retval:InitializeCriticalSection(&crout);初始化臨界變量for(i=0;i5;i+)InitializeCriticalSection(fork + i):/創(chuàng)建五個(gè)哲學(xué)家for(i = 0; i5;i+)argi = i;hthreadi

3、 = CreateThread(NULL, 0, philosopher, (void*) (arg-i), 0, NULL); for(a=0;a30000000;a+);if( hthreadCi = INVALID_HANDLE_VALl:E)/如果線程創(chuàng)建失敗返回Tcerr error while create thread i endl;cerr ,zerror code : GetLastError 0 endl;等待所有線程結(jié)束retval = WaitForMultipleObjects (5, hthread, true, INFINITE); /等待多個(gè)線程 for(a=0

4、;a30000000:a+);if(retval = WAIT.FAILED)cerr wait error, error code: z,GetLastError0endl;for(i = 0; i5;i+)for(a=0;a30000000;a+);i f (C loseHandl e (ht hread i ) = false) /關(guān)閉句柄cerr error while close thread iendl;cerr ,zerror code: /zGetLastError0endl;return 0;DWORD WINAPI ph訂osopher(LPVOID IpParameter

5、) long a=0;int n = (int *)IpParameter)0;for(a=0;a30000000:a+):print(n, is in!);/srand(time(NULL);while(true)thinking(n); waiting(n); eating(n);print(n, is out!);return n;void thinking(int k)long a=0;for(a=0;a30000000;a+):print (k, is thinking);Sleep (1);/Sleep(rand0 %100) *5);void eating(int k)long

6、a=0;for(a=0;a30000000;a+):print (k, is eating);/Sleep(rand 0%100) *5);Sleep (1);LeaveCriticalSection(fork + (k+l)%5); / /放下右邊的筷子/print(k, give left);LeaveCriticalSection(fork + k); /放下左邊的筷子/./print (k, give right);void waiting(int k)long a=0;for(a=0;a30000000;a+):print(k, is waiting);Sleep (1);Enter

7、CriticalSection(fork + k) ;/獲得左邊的筷子/print(k, take left);EnterCriticalSection(fork + (k + 1)%5);/獲得右邊的筷子/print(k, take right);void print(int who, const char *str)tvpedefint semaphore; /*信號(hào)量是一種特殊的整型變量*/semaphore mutex=l; /* 互斥訪問 */semaphore emptv=N;/*記錄緩沖區(qū)中空的槽數(shù)*/semaphore fiill=0; /*記錄緩沖區(qū)中滿的槽數(shù)*/semaph

8、ore buffN; /*有N個(gè)槽數(shù)的緩沖區(qū)bufN,并實(shí)現(xiàn)循環(huán)緩沖隊(duì)列*/ semaphore front=0, rear=0;void p(seniaphore *x) /* p 操作 */ *x=(*x)-l;void v(semaphore *v)/* v 操作 */*y=(*y)+i;void produce_item(int *item_ptr)/*pnntf(Mpioduce ail itemnn);*/*item_ptr=,m,; /* nf is Mmaii 滿;*/ void enter_item(mt x)fiont=(fiont+1 )%N;buffront=x;pnn

9、tf(Mentei_item %c to buf%dn, buffront, front);void remove_item(int *yy)reai(reai+l)%N;printfCemovetem %c fiom buff%d, buffieai, rear);*yy=bufrear;buflreai; /* k is nkong 空” */ pnntf(M so the buff%d changed to empty%ciiH, fear, bufrear);void consume_item(mt y)printf(Mcosume tlie item :tlie screem pri

10、nt %cn9 y); void producer(void); void consumer(void);/*生產(chǎn)者*/void producer(void) mt item;wlule(l)produce_item(&item);p(&emptv);/*遞減空槽數(shù)*/p(&mutex);/*進(jìn)入臨界區(qū)*/enter_item(item); /*將一個(gè)新的數(shù)據(jù)項(xiàng)放入緩沖區(qū)*/ V(&mutex);/*離開臨界區(qū)*/v(&hill);/*遞增滿槽數(shù)/if(fiill=N)/*若緩沖區(qū)滿的話,喚醒消費(fèi)者進(jìn)程*/consumerQ;/*消費(fèi)者*/void consumer(void) mt get_

11、item;wlule(l)p(&fbll);/*遞減滿槽數(shù)*/p(&mutex);/*進(jìn)入臨界區(qū)/remove_item(&g亡/*從緩沖區(qū)中取走一個(gè)數(shù)據(jù)項(xiàng)*/ v(&mutex);/*離開臨界區(qū)*/v(&empty);/*遞增空槽數(shù)*/consume_item(get_item);/*對數(shù)據(jù)項(xiàng)進(jìn)行操作(消費(fèi))*/ if(empty=N)/*若緩沖區(qū)全空的話,喚生產(chǎn)者進(jìn)程*/pioducerO;/*調(diào)用生產(chǎn)者一消費(fèi)者進(jìn)程實(shí)現(xiàn)進(jìn)程間同步*/ niaui()producer();return 0;EEE:0Ssample1Debugsample1.execosune the item :the s

12、creen tt*enoueitem m from buf 2 Losume tlie item : tlie screen tt*enoue_iten m from buf 3 cosune the item :the screen tt*enoueitem m from buf4 cosune the item :the screen tt*enoue_iten m from buf 5 cosune the item :the screen tt*enoue_iten m from buf 6 cosune the item :the screen kemoue_item m f i*o

13、m hif T71 cosune the item :the screen tt*enoueitem m from buf 8 cosune the item :the screen tt*enoueitem m from buf 9 cosune the item :the screen 卜emoue_item m from huf0 item to to to to tocosune the enter_item enter_item enter_item enter_item enter_item傲軌拼首豐::the screen buf 1 buf 12 buf L3 bufL4 bu

14、fL4I printnso thebufL2changedtoemptyki printinso thebuf3changedtoemptyki printnso thebuf4changedtoemptyki printnso thebufL5changedtoemptyki printnso thebuf6changedtoemptyki printnso thebufT71changedtoemptyki printnso thebuf8Jchangedtoemptyki printnso thebuf9changedtoemptyki printnso thebuf0changedto

15、emptyki printn生產(chǎn)者消費(fèi)者問題解決方法二:因?yàn)閷?shí)際情況是生產(chǎn)消費(fèi)速度不會(huì)一致,也不會(huì)想方法一一樣,消費(fèi)完后在生產(chǎn)。我們 生產(chǎn)者要保持滿足消費(fèi)者的需求。調(diào)整下面的數(shù)值,可以發(fā)現(xiàn),當(dāng)生產(chǎn)者個(gè)數(shù)多于消費(fèi)者個(gè) 數(shù)時(shí),生產(chǎn)速度快,生產(chǎn)者經(jīng)常等待消費(fèi)者:反之,消費(fèi)者經(jīng)常等待,可以保證消費(fèi)者可以 一直消費(fèi)。實(shí)現(xiàn)代碼:?tinclude #include const unsigned short SIZE_OF_BUFFER = 10; /緩沖區(qū)長度unsigned short ProductID = 0;unsigned short ConsumelD = 0;/產(chǎn)品號(hào)將被消耗的產(chǎn)品號(hào)unsi

16、gned short in = 0;產(chǎn)品進(jìn)緩沖區(qū)時(shí)的緩沖區(qū)下標(biāo)unsigned short out = 0;產(chǎn)品出緩沖區(qū)時(shí)的緩沖區(qū)下標(biāo)int g.bufferSIZE.OF.BUFFER;/緩沖區(qū)是個(gè)循環(huán)隊(duì)列bool g_continue = true;/控制程序結(jié)束HANDLE g_hMutex;/用于線程間的互斥HANDLE g.hFullSemaphore;當(dāng)緩沖區(qū)滿時(shí)迫使生產(chǎn)考等待HANDLE g.hEmptySemaphore;/當(dāng)緩沖區(qū)空時(shí)迫使消費(fèi)者等待DWORD WINAPI Producer (LPVOID); /生產(chǎn)者線程DWORD WINAPI Consumer (LPVO

17、ID); /消費(fèi)者線程int mainO創(chuàng)建各個(gè)互斥信號(hào)g.hMutex = CreateMutex(XULL, FALSE, NULL);g.hFullSemaphore = CreateSemaphore(NULL, SIZE.OF.BUFFER-l, SIZE_OF_BUFFER-1,NULL); g_hEmp15rSemaphore = CreateSemaphore (NULL, 0, SIZE_OF_BUFFER-1, NULL);調(diào)整下而的數(shù)值,可以發(fā)現(xiàn),當(dāng)生產(chǎn)者個(gè)數(shù)多于消費(fèi)者個(gè)數(shù)時(shí),/生產(chǎn)速度快,生產(chǎn)者經(jīng)常等待消費(fèi)者:反之,消費(fèi)者經(jīng)常等待const unsigned short

18、 PRODUCERS.COUNT = 3;/生產(chǎn)者的個(gè)數(shù)const unsigned short CONSUMERS.COUNT = 1;/消費(fèi)者的個(gè)數(shù)總的線程數(shù)const unsigned short THREADS.COUNT = PRODUCERS.COUNT+CONSUNERS.COUNT:HANDLE hThreadsPRODUCERS_COUNT; 各線程的handleDWORD producer ID CONSUMERS.COUNT; /生產(chǎn)者線程的標(biāo)識(shí)符DWORD consumer ID THREADS.COUXT: /消費(fèi)者線程的標(biāo)識(shí)符創(chuàng)建生產(chǎn)者線程for (int i=O;

19、iPRODUCERS_COUNT;+i)hThreadsiJ =CreateThread(NULL, 0, Producer, NULL, 0, &producerIDi);if (hThreadsi=NULL) return -1;創(chuàng)建消費(fèi)者線程for ( int i=0;iC0NSl3ERS_C0UNT:+i)hThreadsPRODUCERS_COUNT+i=CreateThread(NULL, 0, Consumer, NULL, 0, &consumerIDi);if (hThreadsi=NULL) return -1;while(g_continue) if(getchar()

20、按回車后終止程序運(yùn)行g(shù)_continue = false;return 0;生產(chǎn)一個(gè)產(chǎn)品。簡單模擬了一下,僅輸出新產(chǎn)品的ID號(hào)void Produce 0std:cerr Producing +ProductID std:cerr Succeed std:endl;/把新生產(chǎn)的產(chǎn)品放入緩沖區(qū)void Append0std:cerr ,zAppending a product g_bufferlinZ = ProductID;in = (in+l)%SIZE_OF_BUFFER;std:cerr Succeed std:endl;/輸出緩沖區(qū)當(dāng)前的狀態(tài)for (int i=O;iSIZE_OF_

21、BUFFER;+i) std:cout i : g_bufferi; if (i=in) std:cout - 生產(chǎn); if (i=out) std:cout 消費(fèi); std:cout std:endl;從緩沖區(qū)中取出一個(gè)產(chǎn)品void Take 0std:cerr Taking a product ”; ConsumeID = g_bufferout:out = (out+1)%SIZE_OF_BUFFER;std:cerr Succeed std:endl;/輸出緩沖區(qū)當(dāng)前的狀態(tài)for (int i=O;iSIZE_OF_BUFFER;+i) std:cout i : g_bufferi; if (i=in) std:cout - 生產(chǎn); if (i=out) std:cout 消費(fèi); std:cout std:endl:/消耗一個(gè)產(chǎn)品voi

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論