Valeria
Valeria

Reputation: 1212

pthread mutex with a global variable: correct usage?

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:

  1. Is it really that bad to put the shared resource as a global variable?
  2. If you have only 1 shared variable, like in the example, would it be considered ok to use a global variable, or still no?
  3. What is the better way to share the variables between the processes?

Upvotes: 1

Views: 3191

Answers (2)

Antonio
Antonio

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

cslrnr
cslrnr

Reputation: 747

  1. 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 .

  2. 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.

  3. 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

Related Questions