MFC多线程 临界区问题

wukjong_1988 wukjong_1988 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
最近在学习线程间同步问题,在学习到临界区(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
...全文
评论 2
收藏 已收藏
分享
返回顶部
wukjong_1988
进程/线程/DLL 15,466 成员 49,169 内容