e.g。
EnterCriticalSection ( cs );
LeaveCriticalSection ( cs );
我想创建一个锁定它的函数,并在调用函数调用或离开对象时释放。
如何开始上课?
答案 0 :(得分:2)
这是一个范围广泛的CriticalSection?
class ScopedCriticalSection {
CRITICAL_SECTION cs;
ScopedCriticalSection()
{
if (!InitializeCriticalSectionAndSpinCount(&cs, 0x00000400))
throw std::runtime_error("Could not initialise CriticalSection object");
EnterCriticalSection(&cs);
}
~ScopedCriticalSection()
{
LeaveCriticalSection(&cs);
DeleteCriticalSection(&cs);
}
};
void foo()
{
ScopedCriticalSection scs;
/* code! */
}
答案 1 :(得分:1)
您可以将关键部分包含在具有公共函数Mutex
和acquire
的{{1}}类中,并使用名为release
的第二个类获取构造上的互斥锁并释放它在破坏。
Mutex:
ScopedLock
锁定:
class Mutex {
public:
Mutex() {
//TODO: create cs
}
~Mutex() {
//TODO: destroy cs
}
void acquire() {
EnterCriticalSection(cs);
}
void release() {
LeaveCriticalSection(cs);
}
private:
LPCRITICAL_SECTION cs;
Mutex(const Mutex&); //non-copyable
Mutex& operator=(const Mutex&); //non-assignable
};
像这样使用:
class ScopedLock {
public:
ScopedLock(Mutex* mutex_) : mutex(mutex_) {
mutex->acquire();
}
~ScopedLock() {
mutex->release();
}
private:
Mutex* mutex;
};