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?
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.
<iostream>
... It is not because it is done that way in std
that it is the right way. –
Henig std::mutex
depends on where it's declared---could be global, could be local, could be a private member---just like any other type of variable. Since the purpose of a mutex is to prevent threads from accessing the same data at the same time, it usually makes sense to declare it in the same scope as the data it protects. –
Raouf 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.
© 2022 - 2024 — McMap. All rights reserved.
std::reference_wrapper
;) – Hexapod