Operating System Fundamentals
39 threadA()
{
System.out.print(“Thread A
System.out.println(); Turn = 2
} threadB()
{ While (turn == 1)
;
System.out.print(“Thread B
System.out.println();
} Let us take a quick look to see if this actually does what we want. Notice that we started by setting the shared variable called turn (both A and B can see this) to the value 1. When threadA is finished it sets the value to 2. If we look at threadB() we see that it looks at the value of turn and if it is equal to 1 it does nothing, but we expect that eventually threadA will finish and the value will beset to 2, allowing threadB to execute. This is good this provides us away that allows the two threads to synchronize. It does not matter if threadB gets to run for ten minutes
before threadA even starts, because it will do nothing until threadA is finished. The variable called turn is an example of a
synchronization variable.
Although this solution works, it does pose a bit of a problem. Look again at threadB, we see that it starts with a loop that continuously checks the value called turn. Now if threadB
were to run for five seconds, would the value of turn ever change Of course not, it is threadA that changes it. This
type of checking is called polling and burns a lot of CPU time, which may consume more power from our battery (or may just cause the processor to heat up for no reason.
Share with your friends: