#include <windows.h> #include <iostream> using namespace std; DWORD WINAPI MyThreadProc1(LPVOID lpParameter); //thread data DWORD WINAPI MyThreadProc2(LPVOID lpParameter); DWORD WINAPI MyThreadProc3(LPVOID); //thread data DWORD WINAPI MyThreadProc4(LPVOID); int tickets=100; HANDLE hMutex; int main(){ DWORD tid1=0,tid2=0; //HANDLE handle = CreateThread(NULL,0,MyThreadProc,NULL,0,&tid); HANDLE handle1 = CreateThread(NULL,0,MyThreadProc1,NULL,CREATE_SUSPENDED ,&tid1); HANDLE handle2 = CreateThread(NULL,0,MyThreadProc2,NULL,CREATE_SUSPENDED ,&tid2); ResumeThread(handle1); ResumeThread(handle2); /* int i = 0; for(;i<100;i++) cout<<"Main thread is running"<<endl; */ hMutex = CreateMutex(NULL,FALSE,NULL); Sleep(8000); CloseHandle(handle1); CloseHandle(handle2); cout<< "SubThread1 ID:" << hex << uppercase<< tid1 << endl; cout<< "SubThread2 ID:" << hex << uppercase<< tid2 << endl; cout<<"**************************************************"<<endl; HANDLE handle3 = CreateThread(NULL,0,MyThreadProc3,NULL,0 ,&tid1); HANDLE handle4 = CreateThread(NULL,0,MyThreadProc4,NULL,0 ,&tid2); CloseHandle(handle3); CloseHandle(handle4); system("pause"); return 0; } /* WAIT_OBJECT_0 The state of the specified object is signaled. WAIT_TIMEOUT The time-out interval elapsed, and the object's state is nonsignaled. */ DWORD WINAPI MyThreadProc1( LPVOID lpParameter // thread data ) { //Sleep(20); //int i=0; while(tickets>0){ //WaitForSingleObject(hMutex,INFINITE); DWORD dwCode = WaitForSingleObject(hMutex,5); if(dwCode == WAIT_TIMEOUT){ cout<<endl<<"子线程1 等待超时"<<endl; continue; } cout<<"子线程1卖票:"<<tickets<<endl; --tickets; Sleep(15); ReleaseMutex(hMutex); } return 1; } DWORD WINAPI MyThreadProc2( LPVOID lpParameter // thread data ) { //Sleep(20); //int i=0; while(tickets>0){ //WaitForSingleObject(hMutex,INFINITE); DWORD dwCode = WaitForSingleObject(hMutex,5); if(dwCode == WAIT_TIMEOUT){ cout<<endl<<"子线程2 等待超时"<<endl; continue; } cout<<"子线程2卖票:"<<tickets<<endl; --tickets; Sleep(15); ReleaseMutex(hMutex); } return 1; } DWORD WINAPI MyThreadProc3( LPVOID lpParameter ) { DWORD dwCode = WaitForSingleObject(hMutex,5); if(dwCode == WAIT_TIMEOUT){ cout<<endl<<"子线程3 等待超时"<<endl; } else if(dwCode == WAIT_ABANDONED){ cout<<endl<<"子线程3 WAIT_ABANDONED"<<endl; } cout<<"子线程3运行"<<endl; return 1; } DWORD WINAPI MyThreadProc4( LPVOID lpParameter ) { DWORD dwCode = WaitForSingleObject(hMutex,5); if(dwCode == WAIT_TIMEOUT){ cout<<endl<<"子线程4 等待超时"<<endl; } else if(dwCode == WAIT_ABANDONED){ cout<<endl<<"子线程4 WAIT_ABANDONED"<<endl; } cout<<"子线程4运行"<<endl; return 1; }