Thread generation 07: Use the lock block or Interlocked method to ensure data synchronization of auto-increment variables, lockinterlocked

Source: Internet
Author: User

Thread generation 07: Use the lock block or Interlocked method to ensure data synchronization of auto-increment variables, lockinterlocked

Assume that multiple threads share a static variable. If each thread executes the same method and increases the static variable by 1 each time, is this thread safe? Can Auto-Increment Variable data be synchronized? This article uses the lock block and Interlocked methods to ensure data synchronization of auto-increment variables.

 

□Thread unsafe and data not synchronized

 

    class Program
    {
        static int sum = 0;
        static void Main(string[] args)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            Parallel.For(0, Environment.ProcessorCount, i =>
            {
                for (int j = 0; j < 100000000; ++j)
                {
                    AddOne();
                }
            });
            watch.Stop();
Console. WriteLine ("sum = {0}, using {1}", sum, watch. Elapsed );
            Console.ReadKey();
        }
        static void AddOne()
        {
            sum++;
        }
    }

○ The sum variable is static for all threads to share.
○ Parallel. For provides Parallel Loops. Environment. ProcessorCount indicates the processing of the processor. If there are four CPUs, four cycles are performed.

We found that the result is not the expected 400000000. That is to say, in this case, the auto-increment of static variables is NOT thread-safe. In other words, the synchronization of shared data cannot be guaranteed.

 

□Use the lock statement block to synchronize data

 

The lock block ensures that only one thread enters the block at a time.
    class Program
    {
        static int sum = 0;
        private static readonly object o = new object();
        static void Main(string[] args)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            Parallel.For(0, Environment.ProcessorCount, i =>
            {
                for (int j = 0; j < 100000000; ++j)
                {
                    AddOne();
                }
            });
            watch.Stop();
Console. WriteLine ("sum = {0}, using {1}", sum, watch. Elapsed );
            Console.ReadKey();
        }
        static void AddOne()
        {
            lock (o)
            {
                sum++;
            }
            
        }
    }

This time, use the lock block to obtain the expected results.

 

□Use Interlocked to synchronize data

Interlocked can be used for auto-increment of int or long type variables and ensures type security. The following methods are provided:

 

○ Int Interlocked. Increment (ref int location), auto Increment 1
○ Long Interlocked. Increment (ref long location), auto Increment 1
○ Int Interlocked. Decrement (ref int location), auto-minus 1
○ Long Interlocked. Decrement (ref long location), auto-minus 1
○ Int Interlocked. Add (ref int location, int value), auto-increment value
○ Long Interlocked. Add (ref long location, long value), auto-increment value

 

    class Program
    {
        static int sum = 0;
        static void Main(string[] args)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            Parallel.For(0, Environment.ProcessorCount, i =>
            {
                for (int j = 0; j < 100000000; ++j)
                {
                    AddOne();
                }
            });
            watch.Stop();
Console. WriteLine ("sum = {0}, using {1}", sum, watch. Elapsed );
            Console.ReadKey();
        }
        static void AddOne()
        {
            Interlocked.Increment(ref sum);
        }
    }


Interlocked can also ensure thread security and data synchronization, but it takes a long time.


Summary:
○ The lock block and Interlocked methods can ensure thread security and data synchronization of auto-increment variables.
○ The Interlocked type method is applicable only to int and long variables and has certain limitations.

 

The thread series includes:

Thread series 01, front-end thread, back-end thread, thread synchronization thread series 02, multiple threads simultaneously process a time-consuming task to save time thread series 03, multi-thread shared data, multi-thread data sharing

Thread series 04, passing data to the thread, thread naming, thread Exception Handling, thread pool thread series 05, manual end thread series 06, view the thread pool and Its thread series 07 through CLR code, and use the lock statement block or Interlocked type method to ensure data synchronization of auto-increment Variables
C # Question 2 multi-threaded xml SQL 1

Reply:
Select
Cash payment amount = (select count (*) as from test where type = 1 ),
Cash payment amount = (select sum (*) from test where type = 1
),
Bank payment quantity = (select count (*) from test where type = 2
)
, Bank payment amount = (select count (*) from test where type = 2
)

1. What are the methods for multithreading?

1. When a thread enters moniter (that is to say, the station uses an object), the other thread only waits for or returns, and we call the return mode a pattern in Balking English.

2. These two threads can be executed in an orderly manner, rather than scheduled by the OS. In this case, we need to use an object for scheduling. This mode is called Scheduler. (This word and its meaning are actually included in OS ).

3. If the two threads read a resource at the same time, we can let them execute, But if you write at the same time, you will know that there may be problems with your eyes closed, in this case, we need to use another mode (Read/Write Lock ).

4. If one thread serves another thread, for example, the thread responsible for data transmission in IE and the display thread on the interface, when an image is not transmitted, the other thread cannot be displayed, at least part is not complete. In this case, we need to use a mode called Producer and Consumer. The English mode is Producer-Consumer.

5. The demise of the two threads can not be completely controlled by the operating system. At this time, we need to provide a condition that every thread will die only when the conditions are met, that is, the demise of the order, we call it Two-Phase Termination.

What are the synchronization methods?
I. volatile keywords

Volatile is the simplest synchronization method. Of course, it is easy to pay. It can only perform synchronization at the variable level. volatile means to tell the processor not to put me into the working memory. Please operate on me directly in the main memory. (【

Related Article

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.