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

I saw most examples using std::mutex where the mutex is global. I was wondering if there is any specific reason why this is being done? I had my own programs where I do not do this, and just pass the mutex as std::thread std::ref . Isn't it a bad practice to have global variables, what is the rationality of global std::mutexes in C ++ if there are no language restrictions for this?

+5
source share
2 answers

Bad practice is to have global values, unless it is not. For example, std::cin is global.

Mutexes are, in a sense, global, no matter how you make them. They are shared between disparate pieces of code. That way, you can make them global, or you can pass them along a chain of calls through functions that don't use them until you reach the one who does it. This is known as โ€œtramp dataโ€ as well as โ€œbad practiceโ€. Choose poison.

+4
source

Most likely, this was done to facilitate the execution of the example, allowing the mutex itself to be used as the focus of the example, rather than the exact specification.

Typically, a mutex protects a resource, and in many cases it makes sense for a mutex to live with a resource. For example, if you have a class with a member container that must be protected by a mutex, make the mutex also a member of the class. Then, when an instance of the class acts on multiple threads, the mutex member can be used to protect the necessary accesses to the internal container.

0
source

Source: https://habr.com/ru/post/1269532/


All Articles