CRITICAL_SECTION g_CriticalSection=NULL;
char *g_string=NULL;
class MyClass
{
public:
int InitInstance();
int threadA();
};
int MyClass::Init()
{
InitCriticalSection(&g_CriticalSection);
CreateThread(threadA,...);
}
int MyClass::threadA()
{
EnterCriticalSection(g_CriticalSection)
if(g_string!=NULL)
{
delete g_string;
}
g_string = new char[1024];
...
delete g_string;
g_string = NULL;
ExitCriticalSection(g_CriticalSection)
return 0;
}
2) 如果MyClass改成如下定义,请写出实现上面功能的代码
class MyClass
{
static const CRITICAL_SECTION m_CriticalSection;
public:
MyClass() { EnterCriticalSection(m_CriticalSection); }
~MyClass(){ ExitCriticalSection(m_CriticalSection); }
};
(1)我随便说说看
![](http://www.mscenter.edu.cn/mybbs/faces/1.gif)
int MyClass::Init()
{
InitCriticalSection(&g_CriticalSection);
CreateThread(threadA,...);
}
从代码来看,声明一个MyClass后,应该先调用Init()来初始化,问题就在初始化里面。千不该万不该,不该把临界区的初始化放在类的构造函数里面,这样一来,每初始化一个对象,就要把代表临界资源的变量给初始化一遍,如果这之前已经有对象进入了临界区,那么冲突是不可避免的了。要避免这种情况,最基本的办法就是把临界区的初始化放在一个全局的位置,毕竟临界区变量也是一个全局变量。
(2)如果要2)的要求实现的话
不知道这样行不行:
class MyClass
{
static const CRITICAL_SECTION m_CriticalSection;
public:
MyClass() { EnterCriticalSection(m_CriticalSection); }
~MyClass(){ ExitCriticalSection(m_CriticalSection); }
int threadA();
int Init();
};
int MyClass::Init()
{
CreateThread(threadA,...);
}
int MyClass::threadA()
{
if(g_string!=NULL)
{
delete g_string;
}
g_string = new char[1024];
...
delete g_string;
g_string = NULL;
return 0;
}
int InitCriticalSection(CRITICAL_SECTION* CriticalSection)
{
.............
};
开始时,先调用
InitCriticalSection(&MyClass.m_CriticalSection);
然后再使用MyClass对象