I am reading Thread Synchronization
from the book Advance Programming in unix environment.
In this section, there is a example to use mutex with dynamically allocated object. I have some doubts in the same.
Here I am sharing a timeline of events (top to down) happening to explain my doubts:
ds
. Thread1 need to do very large amount of work with ds
, i.e. Thread1 is going to acquire this lock for a long time. mutex_t
variable before incrementing the count. mutex_t
variable, so when Thread2 call lock()
before incrementig the count, it will have to wait till Thread1 unlock the lock.Doubts:
foo_rele()
to again lock and decrease the count. Now is it possible that before Thread2 increment the count, Thread1 decrements it. If yes (according to me) then my data structure will be destroyed? So I think there is a slight error in this example of the book. It would be better if we use different mutex_var to increment the count? A. I think that under the term "global list" author understands all variables that are shared between threads.
Example:
struct foo* shared_foo; /* This pointer is shared between all threads */
struct foo* foo_alloc(void)
{
/* This pointer is local to the thread which allocates the memory */
struct foo *fp;
if ((fp = malloc(sizeof(struct foo))) != NULL) {
/* whatever */
}
/* local pointer value returned */
return(fp);
}
/* probably somewhere in the code the shared pointer (on the 'global list') is initialized this way */
shared_foo = foo_alloc();
B. Hmm... I don't really undestand what you say. Could you please write your scenario as a list? In my opinion f_count
is set during initialization as a flag 'This mutex is in use'. So when the mutex is free the f_count
value is set to 1. When the Thread1
acquires the lock it's value is set to 2. When it releases the lock the value is set back to 1. Valid f_count
values are: 1 (initalized and free) and 2 (initialized and busy). In order to release the mutex you simply have to call two times foo_rele
when it's taken (f_count
= 2) or once when it's free (f_count
= 1). Then the f_count
value reaches 0 and the mutex is removed.