Thread Series 03, multi-threaded shared data, multithreading does not share data

Source: Internet
Author: User

Multithreaded programming, sometimes you want each thread of data isolation from each other, and sometimes want to share data between the threads, and keep in sync. This article experiences multi-threaded sharing and non-sharing of data.


-Multithreading does not share data

For multi-threading, how does the CLR allocate memory stack space for them? Is "a radish a pit", each thread has its own stack space, or "under the tree to cool", all the threads share the same stack space?

We have 2 threads executing the same static method, using the same variables, and printing variables to verify the allocation of multi-threaded stack space.

    class Program
    {
        Static void Main (string[] args)
        {
            New Thread (Sayhi). Start ();
            Sayhi ();
        }
        Static void Sayhi ()
        {
             for (int i = 0; i < 5; i++)
            {
                Console.WriteLine (" I am Thread #" + Thread.CurrentThread.ManagedThreadId + " This is my first" +i+  " times to say hello ");
            }
        }
    }

Although 2 threads cross-execute, they all say hello for 4 times. Indicates that the CLR allocates stack space for 2 threads, and the variable i is unaffected by each other in the respective stack space.

-Multithreading shared data

How do multiple threads share data between threads that need to work with each other?

※ Shared instance variables

Let 2 threads execute the same instance method to see if the public fields of the object instance can be shared.

using System;
using System.Threading;
namespace ConsoleApplication1
{
    class Program
    {
         Public int whatever;
        Static void Main (string[] args)
        {
            New Program ();
            New Thread (p.printvariable). Start ();
            P.printvariable ();
        }
        void Printvariable ()
        {
            whatever++;
            Console.WriteLine (" Thread #" + Thread.CurrentThread.ManagedThreadId + " whatever variable after execution:" +whatever);
        }
    }
}

As can be seen, 2 threads share the common fields of the program instance.

In addition, about sharing data between threads, a topic that can not be opened is: How to avoid data synchronization? Using the lock statement block solves this problem by allowing only one thread to enter the inside of the method at the same time. This approach is also called "Thread safety."

    class Program
    {
         Public int whatever;
        Static readonly compile-time variables are assigned when declared
        Static ReadOnly Object New Object ();
        Static void Main (string[] args)
        {
            New Program ();
            New Thread (p.printvariable). Start ();
            P.printvariable ();
        }
        void Printvariable ()
        {
            Lock (Locker)
            {
                whatever++;
                Console.WriteLine (" Thread #" + Thread.CurrentThread.ManagedThreadId + " whatever variable after execution:" + whatever);
            }           
        }
    }

When one thread executes in the lock statement block, the other thread waits and waits for the thread to not consume the CPU at that moment.

※ Shared static fields

    class Program
    {
        Static int whatever;
        Static readonly compile-time variables are assigned when declared
        Static ReadOnly Object New Object ();
        Static void Main (string[] args)
        {
            New Thread (printvariable). Start ();
            Printvariable ();
        }
        Static void Printvariable ()
        {
            Lock (Locker)
            {
                whatever++;
                Console.WriteLine (" Thread #" + Thread.CurrentThread.ManagedThreadId + " whatever variable after execution:" + whatever);
            }           
        }
    }

Summarize:
0CLR allocates memory stack space to each thread, and the variables in the stack do not affect each other
0 multithreading can share static fields of the public members and classes of an object instance
0 sharing data between threads requires "thread safety", and using the lock statement block ensures "thread safety"

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 03, multi-threaded shared data, multithreading does not share data

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.