您好,欢迎访问三七文档
当前位置:首页 > 行业资料 > 能源与动力工程 > windows-并发的多线程的应用
(1)苹果香蕉问题#includeiostreamusingnamespacestd;#includewindows.h#includetime.hintk;HANDLEApple_;HANDLEBanana_;CRITICAL_SECTIONmmutex;DWORDWINAPISon(LPVOIDn){//HANDLEApple_;CRITICAL_SECTIONmmutex;inti=1;OpenSemaphore(MUTEX_ALL_ACCESS,false,Apple_);while(1){::WaitForSingleObject(Apple_,INFINITE);//等苹果coutSoneatsiapplesendl;LeaveCriticalSection(&mmutex);i++;}::CloseHandle(Apple_);return0;}DWORDWINAPIDaughter(LPVOIDn){inti=1;//HANDLEBanana_;CRITICAL_SECTIONmmutex;OpenSemaphore(MUTEX_ALL_ACCESS,false,Banana_);while(1){::WaitForSingleObject(Banana_,INFINITE);//等香蕉coutDaughtereatsibananasendl;LeaveCriticalSection(&mmutex);i++;}::CloseHandle(Banana_);return0;}DWORDWINAPIFather(LPVOIDn){UINTfruit;//CRITICAL_SECTIONmmutex;EnterCriticalSection(&mmutex);fruit=rand()%2;if(fruit==0){//盘中放入苹果coutk+1fatherproduceanappleendl;k=k+1;::ReleaseSemaphore(Apple_,1,NULL);}else{//盘中放入香蕉coutk+1fatherproduceabananaendl;k=k+1;::ReleaseSemaphore(Banana_,1,NULL);}return0;}intmain(){intj;k=0;HANDLEFather_[20];Apple_=::CreateSemaphore(NULL,0,1,apple);Banana_=::CreateSemaphore(NULL,0,1,banana);InitializeCriticalSection(&mmutex);srand(time(NULL));for(j=0;j20;j++){Father_[j]=::CreateThread(NULL,0,Father,NULL,0,0);}::CreateThread(NULL,0,Son,NULL,0,0);::CreateThread(NULL,0,Daughter,NULL,0,0);Sleep(1000);WaitForMultipleObjects(20,Father_,TRUE,INFINITE);return0;}(2)苹果桔子问题#includeiostreamusingnamespacestd;#includewindows.h#includetime.hintk;HANDLEApple_;HANDLEOrange_;CRITICAL_SECTIONmmutex;DWORDWINAPISon(LPVOIDn){//HANDLEApple_;CRITICAL_SECTIONmmutex;inti=1;OpenSemaphore(MUTEX_ALL_ACCESS,false,Orange_);while(1){::WaitForSingleObject(Orange_,INFINITE);//等桔子coutSoneatsiorangesendl;LeaveCriticalSection(&mmutex);i++;}::CloseHandle(Orange_);return0;}DWORDWINAPIDaughter(LPVOIDn){inti=1;//HANDLEBanana_;CRITICAL_SECTIONmmutex;OpenSemaphore(MUTEX_ALL_ACCESS,false,Apple_);while(1){::WaitForSingleObject(Apple_,INFINITE);//等苹果coutDaughtereatsiapplesendl;LeaveCriticalSection(&mmutex);i++;}::CloseHandle(Apple_);return0;}DWORDWINAPIFather(LPVOIDn){UINTfruit;//CRITICAL_SECTIONmmutex;EnterCriticalSection(&mmutex);fruit=rand()%2;if(fruit==0){//盘中放入苹果coutk+1fatherproduceanappleendl;k=k+1;::ReleaseSemaphore(Apple_,1,NULL);}else{//妈妈在盘中放入桔子coutk+1motherproduceaorangeendl;k=k+1;::ReleaseSemaphore(Orange_,1,NULL);}return0;}intmain(){intj;k=0;HANDLEFather_[20];Apple_=::CreateSemaphore(NULL,0,1,apple);Orange_=::CreateSemaphore(NULL,0,1,orange);InitializeCriticalSection(&mmutex);srand(time(NULL));for(j=0;j20;j++){Father_[j]=::CreateThread(NULL,0,Father,NULL,0,0);}::CreateThread(NULL,0,Son,NULL,0,0);::CreateThread(NULL,0,Daughter,NULL,0,0);Sleep(1000);WaitForMultipleObjects(20,Father_,TRUE,INFINITE);return0;}
本文标题:windows-并发的多线程的应用
链接地址:https://www.777doc.com/doc-5870138 .html