This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Use of Thread.currentThread.yeald() for busy wait.  RSS feed

 
Kaustubha Raut
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am trying to implement the bakery algorithm for mutual exclusion. For those of you familiar with it, you know that busy waiting is used in it. I have written the following code and it works fine. However, I do not understand why the code wont work if Thread.currenthread().yeald is not use.Why cant I use and let it loop. All the threads get stuck on the second while loops in case yeald is not used..

*Also, during this deadlock,I found the thread numbers to be holding 'numbers' in ascending order.. say Thread 0--> number 230, Thread 1-->231....Thread9-->239,

Is using yeald a wrong way of implementing this classic algorithm?


Following is the psudocode from wikipedia andmy code thereafter



Thanks.
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only because no one has posted a reply to this one, I'll take a vague stab in the dark given the small fragment of the code available. ....

A reason why while (condition) could fail in a scenario like the one you describe is if there is no 'happens between ordering' between the set and read of condition.

the classic example is

while (!stopped)
{
// do something
}

where stopped is set from another thread. In this example when stopped is set from another thread nowt happens if stopped is not volatile (or synchronized block if you were using isStopped etc).

so we need the definition of Global, ie your use of volatile, synchronised etc etc


If this is wrong it won't work and doing things like yield () can fix your problem, prevents a JVM optimisation I seem to remember, note if that was the case your yield code is still not strictly correct just happens to work. (Adding the yield has a couple of side effects that may be fixing your problem, preventing optimisation , entering synchronized block etc etc )


 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!