Elaborate. NET multithreading (six uses Memorybarrier,volatile for synchronization)

Source: Internet
Author: User

The previous section describes the use of semaphores for synchronization, this section focuses on some methods of non-blocking synchronization. This section mainly introduces memorybarrier,volatile,interlocked.

Memorybarriers

This article simply introduces these two concepts, assuming the following code:

Using system;class foo{    int _answer;    BOOL _complete;    void A ()    {        _answer = 123;        _complete = true;    }    void B ()    {        if (_complete) Console.WriteLine (_answer);}    }

If both method A and method B run in two different threads at the same time, can the console output 0? The answer is possible for the following two reasons:

    • The compiler, CLR, or CPU may change the order of instructions to improve performance
    • The compiler, the CLR, or the CPU may optimize the variables through caching, which is not visible to other threads.

The simplest way is to protect variables with Memorybarrier to prevent any form of change order or caching. Calling Thread.memorybarrier will generate a memory fence, and we can solve the problem in the following ways:

Using system;using system.threading;class foo{    int _answer;    BOOL _complete;    void A ()    {        _answer = 123;        Thread.memorybarrier ();    Barrier 1        _complete = true;        Thread.memorybarrier ();    Barrier 2    }    void B ()    {        thread.memorybarrier ();    Barrier 3        if (_complete)        {            thread.memorybarrier ();       Barrier 4            Console.WriteLine (_answer);}}    

In the above example, Barrier1 and Barrier3 are used to ensure that the order of instructions does not change, and Barrier2 and barrier4 are used to ensure that the value changes are not cached. A good solution is to add memorybarrier before and after the variables we need to protect.

In C #, the following operations generate Memorybarrier:

    • Lock Statement (MONITOR.ENTER,MONITOR.EXIT)
    • Methods for all Interlocked classes
    • callback method for thread pool
    • Set or wait signal
    • All methods that rely on the semaphore implementation, such as starting or waiting a task

Because of these behaviors, this code is actually thread-safe:

        int x = 0;        Task t = Task.Factory.StartNew (() = x + +);        T.wait ();        Console.WriteLine (x);    1

In your own program, you may not reproduce the situation described in the above example. In fact, the explanation for Momorybarrier on MSDN is that Momorybarrier is only needed for multicore systems with weaker order protection. But one thing to note: Multithreading to modify variables and not using any shape-shaped locks or memory fences can be a problem.

The following example is a good illustration of the above (in your VisualStudio, choose Release mode, and start without debugging reproduce the problem):

        BOOL complete = false;        var t = new Thread (() =        {            bool toggle = false;            while (!complete) toggle =!toggle;        });        T.start ();        Thread.Sleep (+);        Complete = true;        T.join ();        Blocks indefinitely

This program will never end, because the complete variable is slowly being stored in the CPU register. Adding Thread.memorybarrier to the while loop solves this problem.

volatile keyword

Another more advanced way to solve the above problem is to consider using the volatile keyword. The volatile keyword tells the compiler to generate a fence for each read operation to achieve the purpose of protecting the protection variables. Specific instructions can be found in MSDN Introduction

Volatileread and Volatilewrite

The volatile keyword can only be added to the class variable. Local variables cannot be declared volatile. In this case you may consider using the System.Threading.Volatile.Read method. Let's take a look at how the System.Threading.Volatile source implements these two methods:

    public static bool Read (ref bool location)    {        BOOL flag = location;        Thread.memorybarrier ();        return flag;    }    public static void Write (ref bool location, bool value)    {        thread.memorybarrier ();        location = value;    }

  

At a glance, implemented by Memorybarrier, but he only adds Memorybarrier to the back of the read operation and to the front of the write operation, so you should consider If you first use Volatile.write and then use Volatile.read, is it possible that there is a problem?

In C #, Concurrentdictionary uses volatile classes to protect variables, and interested readers can see how C # Developers use this method to protect variables.

Interlocked

Using Memorybarrier is not always a good solution, especially if you don't need a lock. The Interlocked method provides some common atomic operations to avoid the series of problems mentioned in the previous article. Use interlocked.increment instead of ++,interlocked.decrement to replace the--。 The relevant usage and rationale are described in detail in the MSDN documentation. C # in the source code also often can see interlocked related use.

This paper introduces some synchronization methods in addition to locks and semaphores, and it is welcome to criticize and correct them.

Elaborate. NET multithreading (six uses Memorybarrier,volatile for synchronization)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.