Critical sections and return values ​​in C ++

When trying to create a thread-safe container class from scratch, I ran into the problem of returning values ​​from access methods. For example, on Windows:

myNode getSomeData( )
{
  EnterCriticalSection(& myCritSec);
  myNode retobj;
  // fill retobj with data from structure
  LeaveCriticalSection(& myCritSec);
  return retobj;
}

Now I believe that this type of method is not thread safe, because after the code frees a critical section, another thread can come in and overwrite it immediately retobjbefore the first thread is returned. So, what is an elegant way to return the retobjcaller in thread safe mode?

+5
source share
2 answers

No, it is thread safe because each thread has its own stack and where retobj.

, , - . RAII . - ...

class CriticalLock : boost::noncopyable {
  CriticalSection &section;

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

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

:

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

++, retobj , .

, retobj .

+2

All Articles