Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In what situations would one use the release method of std::unique_lock ? I made the mistake of using the release method instead of the unlock method and it took a while to understand why the following code wasn't working.

#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();
}
like image 624
tcb Avatar asked Feb 13 '15 01:02

tcb


People also ask

What is the benefit of using std :: unique_lock?

There are two primary benefits to using std::unique_lock<> over std::lock_guard<> : you can transfer ownership of the lock between instances, and. the std::unique_lock<> object does not have to own the lock on the mutex it is associated with.

What is std :: unique_lock?

std::unique_lock The class unique_lock is a general-purpose mutex ownership wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.

What is the difference between unique_lock and Lock_guard?

A lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.

Does unique_lock automatically unlock?

look up how a unique_lock() behaves. @Prab, just to give the explanation: unique_lock() is automatically released when the destructor is called meaning it is exception safe and that it automatically unlocks when you leave scope.


1 Answers

There's a good use for it in this answer where ownership of the locked state is explicitly transferred from a function-local unique_lock to an external entity (a by-reference Lockable parameter).

This concrete example is typical of the use: To transfer ownership of the locked state from one object (or even type) to another.

like image 191
Howard Hinnant Avatar answered Oct 05 '22 22:10

Howard Hinnant