用关键段实现线程同步


下面是一段用关键段实现线程同步的例子:

   
  //关键段测试代码
  

#include <iostream>
#include <windows.h>

using namespace std;

CRITICAL_SECTION g_cs;//创建CRITICAL_SECTION结构全局变量

int g_x = 50;

//线程函数1
DWORD WINAPI ThreadFunc1(LPVOID lpParam)
{
while(TRUE)
{
EnterCriticalSection(&g_cs);
cout << "Thread1 get the access to resource" << endl;
if(g_x > 25)
{
Sleep(1);
cout<<"thread1 sell ticket : "<<g_x--<<endl;
}
else
break;

LeaveCriticalSection(&g_cs);
}

return 0;
}

//线程函数2
DWORD WINAPI ThreadFunc2(LPVOID lpParameter)
{
while(TRUE)
{
EnterCriticalSection(&g_cs);
cout << "Thread2 get the access to resource" << endl;
if(g_x > 0)
{
Sleep(1);
cout<<"thread2 sell ticket : "<<g_x--<<endl;
}
else
break;
LeaveCriticalSection(&g_cs);
}

return 0;
}

int main()
{
HANDLE hThread1;
HANDLE hThread2;
InitializeCriticalSection(&g_cs);
hThread1=CreateThread(NULL,0,ThreadFunc1,NULL,0,NULL);
hThread2=CreateThread(NULL,0,ThreadFunc2,NULL,0,NULL);

CloseHandle(hThread1);
CloseHandle(hThread2);

Sleep(4000);
DeleteCriticalSection(&g_cs);

return 0;
}

我在CodeBlocks上面运行这段代码,发现总是只有一个线程函数得以执行,一个线程执行完毕之后就返回了,为什么另外一个线程得不到执行呢?这是为什么呢?运行结果:

请输入图片描述

操作系统 内核 C++

loli控. 13 years, 5 months ago

线程1 break后没有LeaveCriticalSection,导致了问题。
两个线程中都添加类似下面的处理

   
  //线程函数1
  
DWORD WINAPI ThreadFunc1(LPVOID lpParam)
{
while(TRUE)
{
EnterCriticalSection(&g_cs);
cout << "Thread1 get the access to resource" << endl;
if(g_x > 25)
{
Sleep(10);
cout<<"thread1 sell ticket : "<<g_x--<<endl;
}
else
{
LeaveCriticalSection(&g_cs);//add
break;
}

LeaveCriticalSection(&g_cs);
}
cout << "Thread1 exit" << endl;
return 0;
}

畸智的傻逼 answered 13 years, 5 months ago

Your Answer