Critical Sections and return values in C++
Asked Answered
M

2

7

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?

Mesotron answered 25/7, 2012 at 15:20 Comment(3)
But retobj is stored on the stack? Unless it's declared 'static' you should have no problems with the copied data being overwritten.Solothurn
Unless something odd is happening, retobj should be on the stack, and each thread should have its own stack. Race conditions of this sort are more common when you're working with pre-allocated memory and have to lock access to prevent sharing.Inner
@inface, ok good point, so as long as the return value is stored on the stack I'm good.Mesotron
H
8

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.
  ...
} 
Hector answered 25/7, 2012 at 15:24 Comment(0)
V
2

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.

Vocalise answered 25/7, 2012 at 15:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.