请高手帮我分析一下这个多线程的小练习程序。
这个是我按照孙鑫C++视频里面的练习做的 我得编程环境是vs2010+win7
代码如下:
#include<iostream>#include <windows.h>using namespace std;DWORD WINAPI GThreadProc1( __in LPVOID lpParameter );DWORD WINAPI GThreadProc2( __in LPVOID lpParameter );int tickets=100;HANDLE hMutex;int main(){ HANDLE hThread1; HANDLE hThread2; hThread1=CreateThread(NULL,0,GThreadProc1,NULL,0,NULL); hThread2=CreateThread(NULL,0,GThreadProc2,NULL,0,NULL); Sleep(5000); hMutex=CreateMutex(NULL,false,NULL); return 0;}DWORD WINAPI GThreadProc1( __in LPVOID lpParameter ){ WaitForSingleObject(hMutex,INFINITE); while (true) { Sleep(1); if (tickets>0) { cout<<"No.1 seller sells ticket :"<<tickets--<<endl; } ReleaseMutex(hMutex); } return 0;}DWORD WINAPI GThreadProc2( __in LPVOID lpParameter ){ WaitForSingleObject(hMutex,INFINITE); while (true) { Sleep(1); if (tickets>0) { cout<<"No.2 seller sells ticket :"<<tickets--<<endl; ReleaseMutex(hMutex); } } return 0;}
#include<iostream>#include <windows.h>using namespace std;DWORD WINAPI GThreadProc1( LPVOID lpParameter );DWORD WINAPI GThreadProc2( LPVOID lpParameter );int tickets=100;//HANDLE hMutex;CRITICAL_SECTION g_cs;int main(){ HANDLE hThread1; HANDLE hThread2; InitializeCriticalSection(&g_cs); //hMutex=CreateMutex(NULL,false,NULL); hThread1=CreateThread(NULL,0,GThreadProc1,NULL,0,NULL); hThread2=CreateThread(NULL,0,GThreadProc2,NULL,0,NULL); Sleep(5000); CloseHandle(hThread1); CloseHandle(hThread2); DeleteCriticalSection(&g_cs); return 0;}DWORD WINAPI GThreadProc1( LPVOID lpParameter ){ //WaitForSingleObject(hMutex,INFINITE); while (true) { ::EnterCriticalSection(&g_cs); Sleep(1); if (tickets>0) { cout<<"No.1 seller sells ticket :"<<tickets--<<endl; } ::LeaveCriticalSection(&g_cs); //ReleaseMutex(hMutex); } return 0;}DWORD WINAPI GThreadProc2( LPVOID lpParameter ){ //WaitForSingleObject(hMutex,INFINITE); while (true) { ::EnterCriticalSection(&g_cs); Sleep(1); if (tickets>0) { cout<<"No.2 seller sells ticket :"<<tickets--<<endl; //ReleaseMutex(hMutex); } ::LeaveCriticalSection(&g_cs); } return 0;}