Is there any reason C++ 11+ std::mutex should be declared as a global variable instead of passed into a std::thread as a function parameter? Is there any reason C++ 11+ std::mutex should be declared as a global variable instead of passed into a std::thread as a function parameter? multithreading multithreading

Is there any reason C++ 11+ std::mutex should be declared as a global variable instead of passed into a std::thread as a function parameter?


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.


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.