Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BOOST scoped_lock replacement in C++11

Tags:

c++

c++11

boost

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.

like image 577
Wajih Avatar asked Mar 27 '14 02:03

Wajih


Video Answer


1 Answers

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.

like image 180
David Avatar answered Oct 17 '22 16:10

David