简体   繁体   中英

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?

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 ... :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM