[concurrency-interest] Synchronization question

Jeremy Manson jmanson at cs.purdue.edu
Tue Jun 27 18:44:54 EDT 2006

Ryan LeCompte wrote:
> Sounds great. I will make the field volatile. The fact that I ensure
> that the variable is initialized before other threads get a chance to
> read it satisfies the happens-before relationship, correct?

Brian was just saying what I was saying.  As long as you use a
happens-before relationship to make sure the variable is initialized 
before other threads get a chance to read it, you will be okay.

That is, if the variable is x, and there is a volatile boolean variable v:

Writer thread

x = 1;
v = true;

Reader thread:

if (v)
   r1 = x;

The fact that the reader thread won't read x unless v has been set to 
true, plus the fact that the write to x happens-before v is set to true, 
implies that the write to x must happen-before the read of x.


Writer thread:

x = 1;
new Thread(new ReaderThread());

Reader thread:

r1 = x;

The reader thread will not execute until the writer thread has 
initialized x, so the initialization must happen-before the read.

That's the kind of (very obvious) thing you have to do -- you just have 
to use something that is labeled as "this creates happens-before 
relationships" to do it.  So, for example, if v were /not/ volatile in 
the first example, then that wouldn't work, because writes and reads of 
non-volatile variables don't create happens-before relationships.


More information about the Concurrency-interest mailing list