some_id
some_id

Reputation: 29896

How does Mutex scope work

How does mutex scope work exactly.

If I want 3 mutexes for different things and place them as so

static pthread_mutex_t watchdogMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t watchdogCond = PTHREAD_COND_INITIALIZER;
int waitingForGpsSetupThread = 1;

static pthread_mutex_t gpsRunningMutex = PTHREAD_MUTEX_INITIALIZER;
int gpsRunning = 0;

static pthread_mutex_t indoorNavigationRunningMutex = PTHREAD_MUTEX_INITIALIZER;
int indoorSystemRunning = 0;

Are the variables defined within the scope of the first above mutex declaration or how does it work?

Upvotes: 1

Views: 2820

Answers (2)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84189

These are just C variables. It doesn't matter in what order you declare them. What matters is in what order you try to acquire/lock the mutexes if you want to hold them at the same time (as in "always acquire resources in the same order" mantra).

Edit 0:

Looks like you can use some introductory threads material:

I still remember how to google ... :)

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 754570

As written, the three mutexes are all in the same scope. There are no blocks marked by '{...}' to indicate otherwise. The same would be true if the types were all int. From that point of view, a mutex is no different from any other type.

At the point of use, you would do something like:

pthread_mutex_lock(&watchdogMutex);

...operations protected by the watchdog mutex...

pthread_mutex_unlock(&watchdogMutex);

The bit in the middle could be said to be the scope in which the mutex is locked. It would be a very bad idea to have a return statement in the middle of those operations - unless the mutex was also unlocked before returning.

See the POSIX definitions.

Upvotes: 1

Related Questions