Search code examples
c++c++11boost

BOOST scoped_lock replacement in C++11


I am facing a situation where I have to replace a BOOST scoped_lock with an equivalent in C++11. Under visual studio 2013. Since c++11 does not supprt scoped_lock, I am not sure what the replacement code for the following would be. Should I go for lock_guard or try_lock ?

boost::mutex::scoped_lock objectLock(ObjectVectorMutex, boost::try_to_lock);
if (objectLock) {
  // ...
}

And down in the code I have the following 'wait' statement

if (ObjectsCollection.empty()) {
  // This is where we wait til something is filled
  MotionThreadCondition.wait(objectLock);
  ElapsedTime = 0;          
}

Any guidance is much appreciated.


Solution

  • Use std::unique_lock instead of scoped_lock:

    std::unique_lock objectLock(ObjectVectorMutex, std::try_to_lock);
    

    And MotionThreadCondition would be a std::condition_variable, used the same way. However, instead of if(condition) you should do while(condition) to handle spurious wakeups correctly.