Like try_lock on boost :: unique_lock <boost :: mutex>

Like in the header, like try_lock on boost :: unique_lock?

I have this code:

void mySafeFunct() { if(myMutex.try_lock() == false) { return -1; } // mutex ownership is automatically acquired // do stuff safely myMutex.unlock(); } 

Now I would like to use unique_lock (which is also a scope mutez) instead of just boost :: mutex. I want this to avoid all unlock () calls from the function body.

+4
source share
3 answers
 boost::mutex myMutex; boost::unique_lock<boost::mutex> lock(myMutex, boost::defer_lock); lock.try_lock() 
+6
source

You can either delay the lock using the Defer constructor , or use the Try constructor when creating your unique_lock :

 boost::mutex myMutex; boost::unique_lock<boost::mutex> lock(myMutex, boost::try_lock); if (!lock.owns_lock()) return -1; ... 
+10
source

Previous answers may be outdated. I am using boost 1.53 and this seems to work:

 boost::unique_lock<boost::mutex> lk(myMutex, boost::try_to_lock); if (lk) doTheJob(); 
+4
source

Source: https://habr.com/ru/post/1446186/


All Articles