I've seen most examples using std::mutex where the mutex is global. I was wondering is there any specific reason why this is done? I've had programs of my own where I don't do this, and simply pass the mutex in as a std::thread std::ref. Isn't it bad practice to have globals, what is the rational behind global std::mutexes in C++ if there is no language restricting reason to do this?

2

There are 2 best solutions below

7
On

It's bad practice to have globals except when it isn't. 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. That's known as "tramp data" and it's also "bad practice". Choose your poison.

0
On

Most likely this was done to make the example easier to follow, allowing the use of the mutex itself to be the focus of the example rather than the exact specifics.

Typically a mutex protects a resource and in many cases it makes sense for the mutex to live alongside the resource. For example if you have a class with a member container that needs to be protected by a mutex, make the mutex also a member of the class. Then as the class instance is acted on by multiple threads the member-mutex can be used to protect the needed accesses to the internal container.