Thread series 07, using the lock statement block or the interlocked type method to ensure data synchronization of the self-increment variable

Source: Internet
Author: User

Assuming that multiple threads share a static variable, is it thread safe to have each thread execute the same method each time it makes a static variable increment by 1? Can the self-increment variable data be guaranteed to synchronize? This experience uses the lock statement block and the interlocked type method to ensure data synchronization for the self-increment variable.

-Thread insecure, data out of sync practices

    class Program
    {
        Static int sum = 0;
        Static void Main (string[] args)
        {
            New Stopwatch ();
            Watch. Start ();
            Parallel.For (0, environment.processorcount, i =
            {
                 for (int j = 0; j < 100000000; ++j)
                {
                    AddOne ();
                }
            });
            Watch. Stop ();
            Console.WriteLine ("sum={0}, with {1}", Sum, watch. Elapsed);
            Console.readkey ();
        }
        Static void AddOne ()
        {
            sum++;
        }
    }

0 variable sum is static for all threads to share
0parallel.for provides a parallel loop, Environment.processorcount represents processor processing, and if there are 4 CPUs, do 4 groups of loops

We found that the results were not 400000000 of what we expected, that is, static variable self-increment in this case is not thread-safe, in other words, the synchronization of shared data cannot be guaranteed.

-Keep data synchronized via lock statement block

The lock statement block guarantees that only one thread will enter it at the same time.
    class Program
    {
        Static int sum = 0;
        Private Static ReadOnly Object New Object ();
        Static void Main (string[] args)
        {
            New Stopwatch ();
            Watch. Start ();
            Parallel.For (0, environment.processorcount, i =
            {
                 for (int j = 0; j < 100000000; ++j)
                {
                    AddOne ();
                }
            });
            Watch. Stop ();
            Console.WriteLine ("sum={0}, with {1}", Sum, watch. Elapsed);
            Console.readkey ();
        }
        Static void AddOne ()
        {
            Lock (o)
            {
                sum++;
            }
            
        }
    }

This time, the desired result is obtained using the lock statement block.

-Keep data synchronized with interlocked

You can use the Interlocked class for the self-increment of an int or long variable, and for type safety. The methods provided include:

0int interlocked.increment (ref int location), self-increment 1
0long interlocked.increment (ref long location), self-increment 1
0int interlocked.decrement (ref int location), self minus 1
0long interlocked.decrement (ref long location), self-subtract 1
0int interlocked.add (ref int location, int value), self-increment one value
0long Interlocked.add (ref long location, Long value), self-increment one value

    class Program
    {
        Static int sum = 0;
        Static void Main (string[] args)
        {
            New Stopwatch ();
            Watch. Start ();
            Parallel.For (0, environment.processorcount, i =
            {
                 for (int j = 0; j < 100000000; ++j)
                {
                    AddOne ();
                }
            });
            Watch. Stop ();
            Console.WriteLine ("sum={0}, with {1}", Sum, watch. Elapsed);
            Console.readkey ();
        }
        Static void AddOne ()
        {
            Interlocked.Increment (ref sum);
        }
    }


Using interlocked also ensures thread safety and data synchronization, but takes a long time.


Summarize:
0lock statement blocks and interlocked type methods ensure thread safety and data synchronization for self-increment variables
The 0Interlocked type method is only applicable to Int,long type variables and has some limitations

The Thread family includes:

Thread series 01, foreground thread, background thread, thread synchronization thread series 02, multiple threads simultaneously handle a lengthy task to save time thread series 03, multithreading shared data, multithreading does not share data

Thread Series 04, passing data to thread, thread naming, threading exception handling, thread pool thread family 05, manually ending thread thread family 06, viewing thread pool and thread thread family 07 through CLR code, using lock statement block or interlocked type method to guarantee data synchronization of self-increment variables

Thread series 07, using the lock statement block or the interlocked type method to ensure data synchronization of the self-increment variable

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.