The analysis of C # thread synchronization and the thread pool

Source: Internet
Author: User
C # thread synchronization with the thread pool

The example is simple and prepares 5 threads, each of which outputs a number to the console, and then observes the output.

Code Description:

Thread List

private static list<thread> _threadlist;            Static Voidmain (string[] args) {program._threadlist= new list<thread> ();            Attach 5 threads for (inti = 0; i < 5; i++) {program.appendthread ();             }////starts executing all test threads program.executethread ();        Press any key to exit Console.ReadLine ();        }///<summary>///Attach the new test thread to the list of test threads, and the thread execution logic is to output 10 digits///Note that the initialization is set as a background thread, which will ensure that the main thread exits when the other line///process exits automatically </summary> public staticvoid Appendthread () {Program._threadlist.add (Newthread (n                   EW ThreadStart (() = {for (int i = 0; i <; i++)                   {Console.WriteLine (i);        }})) {IsBackground = true}); }///<summary>//Start executing all test threads///</summary> public staticvoid ExeCutethread () {foreach (Thread T in _threadlist) {T.start (); }        }

Observing the results of the execution, we can see the following results:

Depending on the result (the output of the numbers is irregular), there is interference between the threads. The strategy is to add a synchronous member for thread synchronization:

   <summary>        ////multi-threaded synchronized objects        ///</summary> private static Object _syncobj = new Object (); Place lock on thread execution: Program._threadlist.add (Newthread (new ThreadStart (                ) =                {(                    _syncobj)                    {                        for (int i = 0; i < 10;i++)                        {                            Console.WriteLine (i);}}                 )) {IsBackground = true});

Observation results:

You can see that locking a variable with a multi-threaded synchronization through the Lock keyword does allow threads to synchronize.

Now look at the second way:

Use the Monitor keyword to synchronize, code:

Monitor.Enter (_syncobj);                   Try                   {for                       (int i = 0; i <; i++)                       {                            Console.WriteLine (i);                       }                   }                   finally {                       monitor.exit (_syncobj);                   }

Looking at the results, you will see that the threads are synchronized.

The Third Way:

Now let's refactor the code, create a new Threadmanager class, and move the class's responsibilities in:

Class Threadmanager {//<summary>///Thread list///        </summary>        Private staticlist< Thread> _threadlist;         Staticthreadmanager ()        {           _threadlist = new list<thread> ();        }         <summary>        ///Add new thread        ///</summary> public staticvoid appendthread ()        {            Threadmanager._threadlist.add (Newthread (new ThreadStart (                ) =                {for                   (int i = 0; i <; i++)                   {                       Console.WriteLine (i);                   }                 })) {IsBackground = true});        }         <summary>        ///start executing all threads        ///</summary> public staticvoid executethread ()        {            foreach (Thread t in _threadlist)            {                t.start ();}}    }

The code for the main function call changes accordingly:

Static Voidmain (string[] args)        {            ////append 5 threads for            (int i = 0; i < 5; i++)            {                Threadmanager.appendthread ();            }             Start testing            threadmanager.executethread ();             Press any key to continue            console.readline ();        }

Since there is no processing for thread synchronization, the result can certainly be guessed that the thread is not synchronized:

Now Threadmanager This class plus features:[synchronization], run again, found that thread synchronization, this is the thread synchronization of the fourth scenario, it is very simple to use, But first it requires that the execution logic be put in a class, because it ensures that all methods in this class are thread-safe, so its performance is relatively inefficient.

Is there a way to thread synchronization? The answer is yes, that is the fourth method-the thread pool.

Now let's look at how to use the thread pool to implement:

  The static void Main (String[]args)        {/////defines a WaitCallback object and defines its behavior by outputting 10 numbers to the console and passing/////a parameter (this parameter is optional)                       WaitCallback work = new WaitCallback ((o) + =            {for                (int i = 0; i <; i++)                {                   Console.WriteLine (i); 
  }            });             Executes 5 times            for (inti = 0; i < 5; i++)            {/////If you need to pass parameters here, you can call another overloaded method                ThreadPool.QueueUserWorkItem (work) ;            }             Press any key to continue            console.readline ();        }

So you're done with the logic just now? Yes, we can see the results after the run and the threads are synchronized.

What are the benefits of multithreading?

    • The thread pool improves efficiency by reducing the number of threads created, started, and stopped;

    • Using a thread pool allows us to focus on business logic rather than on multithreaded architectures (however, in some cases, manual thread management is preferred)

    • If a foreground thread is required or a priority is set, or the thread in the thread pool is always a background thread, and his priority is default;

    • If you need a thread with a fixed identity to easily exit, hang or discover it by name.

The above is the C # thread synchronization and the thread pool of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.