資源描述:
《第18章___線程同步互斥與進(jìn)程間通信》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫(kù)。
1、同步對(duì)象互斥量事件臨界區(qū)信號(hào)量MFC對(duì)同步對(duì)象的支持互斥的引入(錯(cuò)誤例子)#include#includeHANDLEthread1;HANDLEthread2;inttickets=100;DWORDWINAPIThread1Proc(LPVOIDlparam);DWORDWINAPIThread2Proc(LPVOIDlparam);voidmain(){thread1=CreateThread(NULL,0,Thread1Proc,NULL,0,NULL);t
2、hread2=CreateThread(NULL,0,Thread2Proc,NULL,0,NULL);Sleep(40000);CloseHandle(thread1);CloseHandle(thread2);}DWORDWINAPIThread1Proc(LPVOIDlparam){intt;while(tickets>0){t=tickets;Sleep(100);cout<<"Thread1sell:"<3、Proc(LPVOIDlparam){intt;while(tickets>0){t=tickets;Sleep(100);cout<<"Thread2sell:"<4、utexAttributes,//繼承屬性,可以為空BOOLbInitialOwner,//創(chuàng)建后是否立即擁有訪問權(quán)LPCTSTRlpName);//互斥對(duì)象的名字,為NULL則為匿名互斥對(duì)象功能:創(chuàng)建一個(gè)命名或匿名的互斥對(duì)象,返回句柄函數(shù)返回值:如對(duì)象已存在,則返回原來存在的對(duì)象句柄,創(chuàng)建成功返回新句柄,創(chuàng)建失敗返回NULL互斥對(duì)象相關(guān)函數(shù)DWORDWaitForSingleObject(HANDLEhHandle,//互斥對(duì)象句柄DWORDdwMilliseconds);//等待時(shí)間功能:等待獲取互斥對(duì)象的
5、訪問權(quán),未獲取之前會(huì)一直等待,或用完dwMilliseconds為止,dwMilliseconds可以為0-INFINITE一旦一個(gè)線程獲取了訪問權(quán),函數(shù)會(huì)把互斥對(duì)象置為不可用狀態(tài)函數(shù)返回值為:WAIT_OBJECT_0獲得擁有權(quán),WAIT_TIMEOUT等待超長(zhǎng),WAIT_ABANDONED前擁有者異常終止互斥對(duì)象相關(guān)函數(shù)DWORDWaitForMultipleObjects(DWORDnCount,//數(shù)組中句柄個(gè)數(shù)constHANDLE*lpHandles,//對(duì)象句柄數(shù)組BOOLbWaitAll,//是
6、否等待全部DWORDdwMilliseconds);互斥對(duì)象相關(guān)函數(shù)BOOLReleaseMutex(HANDLEhMutex);功能:釋放對(duì)互斥對(duì)象的訪問權(quán),使互斥對(duì)象處于有信號(hào)(可用)狀態(tài)使用互斥量后的程序#include#includeHANDLEthread1;HANDLEthread2;inttickets=100;DWORDWINAPIThread1Proc(LPVOIDlparam);DWORDWINAPIThread2Proc(LPVOIDlpara
7、m);HANDLEhMutex;voidmain(){thread1=CreateThread(NULL,0,Thread1Proc,NULL,0,NULL);thread2=CreateThread(NULL,0,Thread2Proc,NULL,0,NULL);hMutex=CreateMutex(NULL,false,NULL);while(tickets>0)Sleep(1000);CloseHandle(thread1);CloseHandle(thread2);}DWORDWINAPIThread1
8、Proc(LPVOIDlparam){intt;while(tickets>0){WaitForSingleObject(hMutex,INFINITE);t=tickets;Sleep(100);if(t>0)cout<<"Thread1sell:"<