Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-Blocking Synchronization (MemoryBarrier)

I modified the program given on Non-Blocking Synchronization as following:

class DemoProg
{
    int _answer;
    bool _complete;

    public void StartDemo()
    {
        Thread t1 = new Thread(A);
        Thread t2 = new Thread(B);
        t1.Start();
        // Thread.Sleep(100); // To ensure that B is called after A.
        t2.Start();
    }

    void A()
    {
        for (int i = 0; i < 1000000; i++)
            _answer = 123;
        Thread.MemoryBarrier();    // Barrier 1
        _complete = true;
        Thread.MemoryBarrier();    // Barrier 2
        Console.WriteLine("Exiting A");
    }

    void B()
    {
        //Thread.Sleep(100);
        Thread.MemoryBarrier();    // Barrier 3
        if (_complete)
        {
            Thread.MemoryBarrier();       // Barrier 4
            Console.WriteLine(_answer);
        }
        Console.WriteLine("Exiting B");
    }
}

The article states that they ensure that if B ran after A, reading _complete would evaluate to true. >> they means memory barriers.

Even if i remove memory barriers, there is no change in output. and it's not making sure that if condition results true.

did I interpret it in wrong way?

Thanks.

like image 637
Azodious Avatar asked Apr 20 '26 20:04

Azodious


1 Answers

I talk about this very example here and here.

In a nutshell, the author is correct. Pay very close attention to the statement. In particular, notice that the author says "if B ran after A". He was not saying that the condition will always evaluate true. Instead, the example was contrived to demonstrate one particular nuance of memory barriers.

Furthermore, getting a different result by removing memory barriers will be difficult to reproduce. There are many reasons for this. It is likely due to the environment in which you were running the tests.

like image 134
Brian Gideon Avatar answered Apr 22 '26 21:04

Brian Gideon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!