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:
- Thread1 created.
- Thread1 create a mutex var initialize it and put it on a global list so that other can use it.
- Now Thread1 acquired a lock to use a shared data Structure say
ds. Thread1 need to do very large amount of work withds, i.e. Thread1 is going to acquire this lock for a long time. - Now while Thread1 still acquired the lock, Thread2 is created.
- Now Thread2 also want to use ds.
- So Thread2 has to first increment the counter showing the reference to ds is increased. To do so (according to the book) it first need to acquire a lock using the same
mutex_tvariable before incrementing the count. - But as Thread1 already acquired a lock on this
mutex_tvariable, so when Thread2 calllock()before incrementig the count, it will have to wait till Thread1 unlock the lock.
Doubts:
- About which global list he is talking about (means just to make any list and pass reference of it to all the threads or any specific list)?
- When Thread1 created the lock variable it set the count to 1. Then Thread2 is waiting to increment this count to 2. But suppose a situation in which after doing the current work Thread1 didn’t need to use the ds. So before unlocking it also decrease the count or first unlock it then call
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:
B. Hmm… I don’t really undestand what you say. Could you please write your scenario as a list? In my opinion
f_countis set during initialization as a flag ‘This mutex is in use’. So when the mutex is free thef_countvalue is set to 1. When theThread1acquires the lock it’s value is set to 2. When it releases the lock the value is set back to 1. Validf_countvalues are: 1 (initalized and free) and 2 (initialized and busy). In order to release the mutex you simply have to call two timesfoo_relewhen it’s taken (f_count= 2) or once when it’s free (f_count= 1). Then thef_countvalue reaches 0 and the mutex is removed.