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?
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.
What are global variables in C++? Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of your program. A global variable can be accessed by any function.
Mutex is used to provide synchronization in C++ which means only one thread can access the object at the same time, By the use of Mutex keyword we can lock our object from being accessed by multiple threads at the same time.
Using global variables reduces the modularity and flexibility of the program. It is suggested not to use global variables in the program. Instead of using global variables, use local variables in the program.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With