Reputation: 1212
I understand the purpose of mutex in pthreads, but I often here that it is considered a bad practice to use mutex with a global variable as a shared resource (for example, like in the answer to this question: Mutex lock threads).
So, the questions:
Upvotes: 1
Views: 3191
Reputation: 74
In general:
Global Variable are Evil:
Yes, you have to create a variable in the main thread and pass the reference to other threads that have to use it, which is true even if you have only one shared variable.
Upvotes: 2
Reputation: 747
Is it really that bad to put the shared resource as a global variable?
It depends , It is up to the developer to decide . But in general we need to be cautious about using the shared variable as a global one . For example if the program is so simple , then it is easy to manage global variables , if the program is complex and large enough with its own other complexities , it is somewhat not easy to maintain .
If you have only 1 shared variable, like in the example, would it be considered ok to use a global variable, or still no?
Above answer answers this question as well.
What is the better way to share the variables between the processes?
You can go ahead with some kind of serialization method which suits for you .
Upvotes: 1