MFC多线程 临界区问题

wukjong_1988 2012-03-30 07:15:24
最近在学习线程间同步问题,在学习到临界区(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
...全文
362 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
fishjam 2012-03-30
  • 打赏
  • 举报
回复
你的系统是 Vista或Win7吧?
以前Vista刚出的时候,看到过说刚释放CriticalSection如果又获取的话会优先获得,当时这好像是个Bug,要求我们用Mutex来代替。
你可以尝试将 CriticalSection 换成 Mutex,应该会出现两个线程交替输出的结果。
wukjong_1988 2012-03-30
  • 打赏
  • 举报
回复
搞定!

在LeaveCriticalSection后面加个sleep(1)就搞定,自己理解的是在离开临界区如果没有休眠下,自己又马上获得临界区资源,这样其他线程得不到临界区。我自己理解:系统不会不会通知另一个需要获取临界区的线程,需要临界区的线程只是在循环的询问这个临界区是否可以进入。

15,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧