views:

49

answers:

3

Hi,

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,

+2  A: 

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.

Mitch Wheat
ah good point, i missed that.
darren
I'm using java. flag is a global variable, declared static. Don't know if this helps :)
pinpinlelapin
Static variables are not automatically volatile.
Mike Daniels
A: 

(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.

Jeremy Friesner
A: 

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.

Ed Marty
incorrect, flag might be cached in a register
Mitch Wheat
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