mardi 26 octobre 2021

std::lock_guard and std::adopt_lock behaviour without locking the mutex

I have been learning about the usage of std::lock and std::lock_guard and most examples follow the pattern below:

std::lock(m1, m2);
std::lock_guard<std::mutex> guard1(m1, std::adopt_lock);
std::lock_guard<std::mutex> guard2(m2, std::adopt_lock);
//Do something here

Then I came across an example that utilized the same pattern you would use if you were using std::unique_lock, but with lock_guard:

std::lock_guard<std::mutex> guard1(m1, std::adopt_lock);
std::lock_guard<std::mutex> guard2(m2, std::adopt_lock);
std::lock(m1, m2);
//Do something here

My question is, would this cause undefined behaviour if you use the second pattern and an exception occurs before you reach std::lock?

P.S. I am aware that C++17 introduced std::scoped_lock and that std::lock_guard is still around mainly for compatibility with older code.

Aucun commentaire:

Enregistrer un commentaire