Critical Sections和C ++中的返回值 [英] Critical Sections and return values in C++
问题描述
在尝试从头创建线程安全容器类时,我遇到了从访问方法返回值的问题。例如在Windows中:
In attempting to create a thread-safe container class from scratch, I've run into the problem of returning values from access methods. For example in Windows:
myNode getSomeData( )
{
EnterCriticalSection(& myCritSec);
myNode retobj;
// fill retobj with data from structure
LeaveCriticalSection(& myCritSec);
return retobj;
}
现在我想这种类型的方法不是线程安全的,因为在代码释放临界区之后,另一个线程能够在第一个线程返回前立即覆盖 retobj
。那么,什么是一个优雅的方式以线程安全的方式返回 retobj
给调用者?
Now I suppose that this type of method is not at all thread-safe because after the code releases the critical section another thread is able to come along and immediately overwrite retobj
before the first thread returns. So what is an elegant way to return retobj
to the caller in a thread-safe manner?
推荐答案
不,它是线程安全的,因为每个线程都有自己的堆栈,这是 retobj
的地方。
No, it's thread-safe because each thread has it's own stack, and that's where retobj
is.
但是,它肯定不是异常安全的。将关键部分包装在RAII样式对象中将有所帮助。像... ...
However, it's certainly not exception-safe. Wrap the critical section in a RAII-style object would help that. Something like...
class CriticalLock : boost::noncopyable {
CriticalSection §ion;
public:
CriticalLock(CriticalSection &cs) : section(cs)
{
EnterCriticalSection(section);
}
~CriticalLock()
{
LeaveCriticalSection(section);
}
};
用法:
myNode getSomeData( )
{
CriticalLock lock(myCritSec); // automatically released.
...
}
这篇关于Critical Sections和C ++中的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!