Critical Sections and return values in C++

夙愿已清 提交于 2019-12-05 04:40:50

No, it's thread-safe because each thread has it's own stack, and that's where retobj is.

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 &section;

public:
  CriticalLock(CriticalSection &cs) : section(cs)
  {
    EnterCriticalSection(section);
  }

  ~CriticalLock()
  {
    LeaveCriticalSection(section);
  }
};

Usage:

myNode getSomeData( )
{
  CriticalLock  lock(myCritSec);  // automatically released.
  ...
} 

This is C++, and retobj has automatic storage type, so it's stored on the stack.

Every thread has its own stack, so another thread cannot clobber the value of retobj before it is returned.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!