Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Critical Sections and return values in C++

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;
}

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?

like image 851
ThomasMcLeod Avatar asked Jul 25 '12 15:07

ThomasMcLeod


1 Answers

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.
  ...
} 
like image 98
Roddy Avatar answered Sep 16 '22 17:09

Roddy