如果想要某些事情成对出现,使用构造函数和析构函数。
为保证线程同步/互斥,经常使用信号量、互斥量、临界区和事件。以临界区 CRITICAL_SECTION 为例,需要
InitializeCriticalSection 和 DeleteCriticalSection
EnterCriticalSection 和 LeaveCriticalSection
成对配合使用,否则可能出现资源泄漏甚至死锁的情况。
考虑以下程序片段,中间的代码可能出现异常,导致控制转移。或者函数有多个出口,就需要在每个出口前调用LeaveCriticalSection。
点击(此处)折叠或打开
-
CRITICAL_SECTION _cs;
-
void SomeFunc()
-
{
-
EnterCriticalSection(&_cs);
-
-
//可能抛出异常
-
-
LeaveCriticalSection(&_cs);
- }
点击(此处)折叠或打开
-
#include <Windows.h>
-
-
class Lock
-
{
-
public:
-
Lock();
-
~Lock();
-
void Enter(int id = 0);
-
void Leave();
-
private:
-
CRITICAL_SECTION _cs;
-
DWORD dwOwningThread;
-
int iEnterCount;
-
int iId;
-
};
-
-
class AutoLock
-
{
-
public:
-
AutoLock(Lock* target, int id = 0);
-
~AutoLock();
-
private:
-
Lock* _target;
- };
点击(此处)折叠或打开
-
#include <Windows.h>
-
-
class Lock
-
{
-
public:
-
Lock();
-
~Lock();
-
void Enter(int id = 0);
-
void Leave();
-
private:
-
CRITICAL_SECTION _cs;
-
DWORD dwOwningThread;
-
int iEnterCount;
-
int iId;
-
};
-
-
class AutoLock
-
{
-
public:
-
AutoLock(Lock* target, int id = 0);
-
~AutoLock();
-
private:
-
Lock* _target;
- };
点击(此处)折叠或打开
- Lock* workBufferLock;
-
//...
-
AutoLock lock(workBufferLock);
- //...
【参考】
Solmyr 的小品文系列之六:成对出现
Solmyr 的小品文系列之六:成对出现
转: http://blog.csdn.net/lilypp/article/details/6617830