MFC多线程 临界区问题
最近在学习线程间同步问题,在学习到临界区(CriticalSection)的时候,出现了理解不了的现象,网上也有搜到过遇到过这个问题的帖子,但是没有满意的答案。 我遇到的问题是,输出结果只有线程1或者线程2,不是线程间切换的输出。 请高手指点啊~
#include <windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI Fun1Proc(LPVOID lpParameter);
DWORD WINAPI Fun2Proc(LPVOID lpParameter);
int tickets=10;
CRITICAL_SECTION g_cs;
void main()
{
cout << "Main thread is running." << endl;
InitializeCriticalSection(&g_cs);
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
SetThreadPriority(hThread1, THREAD_PRIORITY_NORMAL);
SetThreadPriority(hThread2, THREAD_PRIORITY_NORMAL);
CloseHandle(hThread1);
CloseHandle(hThread2);
Sleep(2000);
DeleteCriticalSection(&g_cs);
}
DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
while(TRUE)
{
EnterCriticalSection(&g_cs);
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell ticket : "<<tickets--<<endl;
}
LeaveCriticalSection(&g_cs);
if (tickets <= 0)
{
break;
}
}
return 0;
}
DWORD WINAPI Fun2Proc(LPVOID lpParameter)
{
while(TRUE)
{
EnterCriticalSection(&g_cs);
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell ticket : "<<tickets--<<endl;
}
LeaveCriticalSection(&g_cs);
if (tickets <= 0)
{
break;
}
}
return 0;
}
输出结果:
Main thread is running.
thread2 sell ticket : 10
thread2 sell ticket : 9
thread2 sell ticket : 8
thread2 sell ticket : 7
thread2 sell ticket : 6
thread2 sell ticket : 5
thread2 sell ticket : 4
thread2 sell ticket : 3
thread2 sell ticket : 2
thread2 sell ticket : 1
Press any key to continue