Suppose I have code like this:
#include "boost/thread/mutex.hpp" using boost::mutex; typedef mutex::scoped_lock lock; mutex mut1, mut2; void Func() {
If test_raiicomma_1 () was called from multiple threads, it blocks the mutex to prevent another thread from calling Func() at the same time. A mutex is locked when mut1_lock built and released when it goes out of scope and collapses.
This works fine, but depending on the style, I needed to give a name to the temporary object holding the lock. The test_raiicomma_2() function tries to avoid this by initializing the lock object and calling the Func() function within the same expression.
Is it true that the temporary object's destructor will not be called until the end of the expression after Func() returns? (If so, do you think itโs ever worthwhile to use this idiom, or is it always clear to declare the lock in a separate statement?)
If it is necessary to lock two mutual values โโfor the test_raiicomma_3() function, is it true that the mutexes will be locked in order before calling Func() and released later, but can, unfortunately, be released in any order?
source share