• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

My Semaphore

 
Swerrgy Smith
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
22
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic