c++ - How to use lock_guard in this conditional -
a thread has following control flow:
mutex.lock() if (condition) { // synced things mutex.unlock(); // parallel things } else { // other synced things mutex.unlock(); // other parallel things } note how 4 do parts execute different things.
how replace direct calls lock , unlock using std::lock_guard instead?
std::unique_lock looks you're looking for. semantics similar std::lock_guard, allows more sophisticated constructs. in case still exception safety, can explicitly unlock early. like:
std::unique_lock<decltype(mutex)> guard(mutex); // calls mutex.lock() lock_guard if (condition) { // synced things guard.unlock(); // parallel things } else { // other synced things guard.unlock(); // other parallel things } // unlocks on leaving scope, if held similar lock_guard
Comments
Post a Comment