Re: What's difference between memory_order_relaxed and no memory order in c++0x?

Discussion in 'C++' started by Anthony Williams, Sep 14, 2010.

  1. kuangye <> writes:

    > What's difference between memory_order_relaxed and no memory order in c
    > ++0x?
    >
    > /*
    > The following code sample is from
    > http://www.justsoftwaresolutions.co.uk/threading/memory_models_and_synchronization.html
    > */
    >
    > std::atomic<int> x(0),y(0);
    >
    > void thread1()
    > {
    > x.store(1,std::memory_order_relaxed);
    > y.store(1,std::memory_order_relaxed);
    > }
    >
    > void thread2()
    > {
    > int a=y.load(std::memory_order_relaxed);
    > int b=x.load(std::memory_order_relaxed);
    > if(a==1)
    > assert(b==1); // no guarantee that b==1 when a==1
    > }
    >
    > std::thread t1(thread1);
    > std::thread t2(thread2);
    >
    >
    > --------------------------------------------------------------------------------------------
    > If I replace the atomic<int> with int ( as the following code). what
    > will happen??


    Undefined behaviour. You have two non-atomic accesses to a variable, one
    of which is a write, with no defined order between them. This is
    therefore a data race and undefined behaviour.

    > Therefor, what's difference between memory_order_relaxed and no memory
    > order in c++0x?


    The use of atomics with memory_order_relaxed make it defined
    behaviour. With atomics, the value of x is either 0 or 1, the same for
    y. With plain int the program has undefined behaviour and may format
    your hard disk.

    > Does memory_order_relaxed prevent c++ compiler from code reordering or
    > anything else ??


    It ensures that the compiler uses the correct instructions for atomic
    operations on the target CPU. It also may potentially inhibit some
    optimizations.

    Anthony
    --
    Author of C++ Concurrency in Action http://www.stdthread.co.uk/book/
    just::thread C++0x thread library http://www.stdthread.co.uk
    Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
    15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976
     
    Anthony Williams, Sep 14, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page