Take the 2-minute tour ×

Say there's a statement waiting for a variable to be updated by another thread.

#in thread1:
while (flag == 0);

Without using any kind of lock, there might be a read-write conflict if one thread reads the variable while it's being updated by another one.

#in thread2:
flag = 1;

Can this lead to an infinite loop? or is the conflict only going to delay the thread #1 ?

Thanks in advance,

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

If flag is not marked as volatile, then it may not get updated, because the while loop code might be referencing the value cached in a register.

share|improve this answer
ah good point, i missed that. –  darren Jan 14 '10 at 4:17
I'm using java. flag is a global variable, declared static. Don't know if this helps :) –  pinpinlelapin Jan 14 '10 at 4:23
Static variables are not automatically volatile. –  Mike Daniels Jan 14 '10 at 4:35
add comment

(assuming c/c++): If (flag) isn't declared volatile, thread1 might be reading flag's value out of a register, so it might never see that thread2 changed flag's memory location to 1, and thus thread1 might continue looping forever even though thread2 set flag to 1.

Another possibility could be that thread1 runs at higher priority than thread2, so thread2 never gets a chance to run and set flag=1, because thread1 is hogging the CPU all to itself, forever.

share|improve this answer
add comment

As shown there, if nothing else is going on, as long as the line in thread 2 every gets to execution, then thread1 will not be in the infinite loop you described above. In most cases, since threads do not, in fact, execute concurrently, both lines cannot be executing at the same time, unless you are running on multiple CPU cores.

Notice that I had to be very careful with my wording, because there are so many other things that could go wrong.

share|improve this answer
incorrect, flag might be cached in a register –  Mitch Wheat Jan 14 '10 at 4:18
Sorry, my mistake. I've been working in other languages lately. So, there's that. Ny answer still stands, as long as volatile is there. –  Ed Marty Jan 14 '10 at 14:35
add comment

Your Answer


