Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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?

like image 688
Krupip Avatar asked Jul 05 '17 17:07

Krupip


People also ask

Should mutex be a global variable?

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.

Why do we use global variables in C++?

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.

Why do we use mutex in C++?

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.

Should you use global variables in C++?

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.


1 Answers

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.

like image 90
Pete Becker Avatar answered Oct 13 '22 15:10

Pete Becker