首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VC/MFC >

MFC多线程 临界区有关问题

2012-04-28 
MFC多线程 临界区问题最近在学习线程间同步问题,在学习到临界区(CriticalSection)的时候,出现了理解不了的

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

[解决办法]
你的系统是 Vista或Win7吧?
以前Vista刚出的时候,看到过说刚释放CriticalSection如果又获取的话会优先获得,当时这好像是个Bug,要求我们用Mutex来代替。
你可以尝试将 CriticalSection 换成 Mutex,应该会出现两个线程交替输出的结果。

热点排行