locked
Chained volatile writes/reads RRS feed

  • Question

  • Hello.

    I would like to submit you this particular example and to get your opinion:

     

    Class members:

    Object _o;

    volatile bool _b1;

    volatile bool _b2;

     

    2 background threads:

    void Thread1Background()

    {

    while(!_b1){Thread.Sleep(0);};

    // _o would be seen as not null here, but we don't access it yet.

    _b2=true;

    }


    void Thread2Background()

    {

    while(!_b2){Thread.Sleep(0);};

    Console.WriteLine(_o.ToString());   // Am I GARANTEED to see _o not null here?

    }

     

    And the entry point:

    void Main(string[])

    {

    MyClass myinstance=new MyClass();

    Thread.Start(myinstance.Thread1Background);

    Thread.Start(myinstance.Thread2Background);


    myinstance. _o=new Object();

    myinstance._b1=true;   // volatile write starts the whole thing.

    }

     

    The question is: according only to langage spec (meaning on any platform including Itanium or other future low memory coherency platforms) am I garanteed to see _o as not null in WriteLine() in Thread2Background?

     

    Here we have chained volatile writes/reads:

    Volatile write/read to/from _b1 garantees that _o would be seen as not null in Thread1Background.

    But another volatile write read (to ANOTHER member, _b2) is chained behind and causes Thread2Background (which may run on another core) to access _o.

     

    I guess that the answer is: YES, as soon as we are sure that WriteLine occurs AFTER the volatile read to _b1 (no reordering thanks to volatile _b2), any thread will read the non null value.

    But I can't find any real clue for that in langage specs or sample codes (except maybe variable initializers, which runs in background threads, and are probably synched with the constructor thread with a volatile write/read).

    Your help is welcome! :)

    Sunday, July 11, 2010 8:58 AM

All replies