locking - C and pthreads: how can a mutex be referred to a particular variable? -


in this code example of use of mutex showed. in particular, mutex first declared before main:

pthread_mutex_t mutexsum; 

the particular variable "protected" mutex dotstr.sum in global structure dotstr: every thread writes on after having acquired lock. correspondant code is:

pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("thread %ld did %d %d:  mysum=%f global sum=%f\n",offset,start,end,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); 

i have compiled code , works, don't know mutexes well. so, how can program aware "general" mutex mutexsum applied on dotstr.sum variable?

there many other global variables can locked. why there not explicit relation in code between mutex mutexsum , variable want lock, dotstr.sum?

a (pthread) mutex isn't explicitly bound particular variable, it's general locking mechanism. it's make sure every action on variable surrounded locks , unlocks.

your program has a(n implicit) contract 1 thread may access dotstr.sum. mutex helps enforce making sure 1 thread can have lock on mutex, won't force lock , unlock everytime dotstr.sum.

try, example, commenting out lock & unlock lines. program still compile , run, result may not wanted be.

you can associate mutex anything, example reading or writing file. you must make sure every access thing want lock locked.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -