I have a global variable flag
, a function this()
, and a function that()
. Now, main()
, this()
and that()
all have occasions where they need to read and/or write flag
. To properly use a mutex I would need to:
- declare a
pthread_mutex_t
and initialize it. - create threads for
this()
andthat()
andpthread_join()
them because I wantmain()
to wait onthis()
andthat()
to finish before exiting. - anywhere in the code, be it
main()
,this()
, orthat()
, whereflag
is being read or written, callpthread_mutex_lock()
then [read/write]flag
then callpthread_mutex_unlock()
Is that correct?
I don't plan on doing this but if I want to check flag
in an infinite loop in main()
like this:
while(flag != value)
continue;
Where would you lock()
and unlock()
the mutex and would the other threads get a chance to access flag
with main()
being constantly all over it like that?