Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::mutex best practice

Since when an exception is thrown the only code is ensured to being run is the destructor, code like this might generate a memory leak

std::mutex foo;
foo.lock();
// My code which might throw an exception
foo.unlock();

Is it a best practice do something similar to this or might there is other better option? The idea is taking advantage of RAII in order to ensure than mutex will be freed if exception is thrown.

std::mutex foo;
{
    std::lock_guard<std::mutex>(foo);
    // My code which might throw an exception
}
like image 636
arturn Avatar asked Jun 18 '19 08:06

arturn


People also ask

Is std :: mutex fair?

On windows e.g. mutexes are mostly fair, but not always. Some implementations e.g. Thread Building Block provide special mutexes that are fair, but these are not based on the OSes native mutexes, and are usually implemented as spin-locks (which have their own caveats). Save this answer.

Should mutexes be global?

For example, std::cin is global. Mutexes are in a sense global, regardless of how you make them available. They're shared between disparate pieces of code. So you can make them globals, or you can pass them down the call chain, through functions that don't use them, until you eventually reach someone who does.

Is a STD mutex thread safe?

Shared mutexes and locks are an optimization for read-only pieces of multi-threaded code. It is totally safe for multiple threads to read the same variable, but std::mutex can not be locked by multiple threads simultaneously, even if those threads only want to read a value. Shared mutexes and locks allow this.

What is the benefit of using std :: unique_lock <> between instances?

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.


1 Answers

Is it a best practice do something similar to this?

std::mutex foo;
{
    std::lock_guard<std::mutex>(foo);
    // My code which might throw an exception
}

No! You are creating an unnamed temporary variable here with a lifetime that ends at the end of the line. Instead, make sure that the object has a name, such that its lifetime meets that of its scope.

std::mutex foo;
{
    std::lock_guard<std::mutex> NEVER_FORGET_THIS_NAME(foo);
    // My code which might throw an exception
}

But besides, generally - yes, it is good practice to use RAII in this situation. And also note that the unnamed-lockguard bug is not uncommon, have a look here.

like image 147
lubgr Avatar answered Sep 22 '22 06:09

lubgr