Synchronization without blocking (MemoryBarrier)

I changed the program specified in Non-Blocking Synchronization as follows:

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 says that they ensure that if B ran after A, reading _complete would evaluate to true.→ they mean memory barriers.

Even if I remove the memory barriers, no changes in the output occur. , and this does not guarantee that if the condition is true.

Did I interpret this incorrectly?

Thank.

+3
source share
1 answer

I will talk about this example here and here .

, . . , , " B ". , . , .

, . . , , .

+1

All Articles