What are the use cases for std :: unique_lock :: release?

In what situations can the release std::unique_lock method be used? I made a mistake using the release method instead of the unlock method, and it took some time to figure out why the following code didn't work.

 #include <mutex> #include <iostream> #include <vector> #include <thread> #include <chrono> std::mutex mtx; void foo() { std::unique_lock<std::mutex> lock(mtx); std::cout << "in critical section\n"; std::this_thread::sleep_for(std::chrono::seconds(1)); lock.release(); } int main() { std::vector<std::thread> threads; for (int i = 0; i < 5; ++i) threads.push_back(std::thread(foo)); for (std::thread& t : threads) t.join(); } 
+5
source share
2 answers

.release() is useful if you want to lock the mutex until some other object / code decides to unlock it ... for example, if you called a function that required locking the mutex, and it itself would unlock its specific point in this function , where this function accepts only std::mutex& , and not std::unique_lock<std::mutex>&& . (Conceptually similar to using smart pointer release functions.)

+5
source

It’s good to use this answer for it, where ownership of the locked state is explicitly transferred from the unique_lock to an external entity (a -reference Lockable).

This specific example is typical for use: transfer ownership of a locked state from one object (or even type) to another.

+6
source

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


All Articles