| Author |
My Semaphore
|
Swerrgy Smith
Ranch Hand
Joined: Mar 26, 2010
Posts: 50
|
|
Hi all,
I have implemented a Semaphore below, it seems to work well. However if in the method acquire() I replace [while (count==0)] by [if (count==0)] then the Semaphore doesn't work well anymore.
For me, there is nothing different, because if count==0 then the current thread will sleep. When the thread is notified, it will continue to execute from the code after wait() (that means it will not check the condition count==0 again). If so, [while (count==0)] and [if (count==0)] are the same.
Is this true?
Thank you very much.
|
 |
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 3090
|
|
Swerrgy Smith wrote:... When the thread is notified, it will continue to execute from the code after wait() (that means it will not check the condition count==0 again). If so, [while (count==0)] and [if (count==0)] are the same.
Is this true?
That would only be true if you could rely that your object would only be notified when the release() method was called. That is not the case - there is a chance (a real chance) of of what the API calls spurious notifications and interruptions. You need to handle that case, or you will get into trouble with a thread coming out of the wait() when there is no count available.
|
Steve
|
 |
 |
|
|
subject: My Semaphore
|
|
|