"Multithreading-Thread Synchronization"

Source: Internet
Author: User

Thread synchronization: Coordinate concurrent operations between multiple threads to achieve the expected, determined execution results and eliminate the uncertainty of multithreaded applications.

Use thread synchronization: You can protect resources at the same time only by one thread access, the general action is to acquire locks, release locks. The lock mechanism; the order in which threads are accessed can be reconciled, that is, a resource can be accessed first by thread A, and then by thread B.

    Class program    {        private static Thread subthread;        private static int i;        static void Main (string[] args)        {            subthread = new Thread (new ThreadStart (getshow));            Subthread. Start ();   Turn on thread            getshow ();            Console.WriteLine ("{0} background thread", thread.currentthread.name+thread.currentthread.isbackground+ ", End");        }        static void Getshow ()        {            Console.WriteLine (i);            i++;            Console.WriteLine (i);        }    }

The above code execution time, there are two threads to access the same resource at the same time, the output to the console to perform the i++ operation, so that the two threads come in that moment, the value of I does not change is still 0, but after the execution of the i++ value has changed, commented out the following output run program found: Output 2 after the output is 1 , which is also a difference in the output order of the values resulting from the indeterminate execution order of the threads.


Resource protection with monitor using exclusive locks 1. Use objects as lock objects:
Class program    {        private static Thread subthread;        private static int i;        private static Object obj = new Object ();        static void Main (string[] args)        {            Thread.CurrentThread.Name = "Master";            Subthread = new Thread (new ThreadStart (getshow));            Subthread. Name = "Subject";            Subthread. Start ();   Turn on thread            getshow ();            Console.WriteLine ("{0} background thread", thread.currentthread.name+thread.currentthread.isbackground+ ", End");        }        static void Getshow ()        {            monitor.enter (obj);//Gets an exclusive lock on the specified object.            Console.WriteLine (thread.currentthread.name+ ">>" +i);            i++;            Console.WriteLine (thread.currentthread.name+ ">>" +i);            Monitor.Exit (obj); Releases an exclusive lock on the specified object.        }    }


Use System.Type to lock objects: Modify the above method: The result of the operation is consistent with the above.
<span style= "White-space:pre" ></span>static void Getshow ()        {            Monitor.Enter (typeof (program)); /Gets an exclusive lock on the specified object.            Console.WriteLine (thread.currentthread.name+ ">>" +i);            i++;            Console.WriteLine (thread.currentthread.name+ ">>" +i);            Monitor.Exit (typeof (program)); Releases an exclusive lock on the specified object.        }
Use lock locking: If the previous code in the above Monitor.Exit (program) has an exception, the main thread throws an exception when executing to an exception, which can be handled by: Try Catch Finall:
            Try            {                Console.WriteLine (Thread.CurrentThread.Name + ">>" + i);                i++;                Console.WriteLine (Thread.CurrentThread.Name + ">>" + i);                throw new Exception ("ASDASD");            }            Catch            {            }            finally            {                monitor.exit (typeof (Program));//releases an exclusive lock on the specified object.            }
Use lock to simplify: the implementation effect is the same as above.
            Lock (typeof (program))            {                try                {                    Console.WriteLine (Thread.CurrentThread.Name + ">>" + i);                    i++;                    Console.WriteLine (Thread.CurrentThread.Name + ">>" + i);                    throw new Exception ("ASDASD");                }                Catch {}            }
For the [MethodImpl (methodimploptions.synchronized)] tag to create the security type of the thread, you can use [MethodImpl (methodimploptions.synchronized)] To mark:

        [MethodImpl (methodimploptions.synchronized)]//marked with        static void Getshow ()        {            try            {                Console.WriteLine (Thread.CurrentThread.Name + ">>" + i);                i++;                Console.WriteLine (Thread.CurrentThread.Name + ">>" + i);                throw new Exception ("ASDASD");            }            Catch {}        }
Use Monitor to reconcile thread execution order:
    Class program    {        private static Thread subthread;        static void Main (string[] args)        {program            p=new program ();            Thread.CurrentThread.Name = "Main thread";            Subthread = new Thread (new ThreadStart (p.getshow));            Subthread. Name = "Child thread";            Subthread. Start ();   Turn on thread            Lock (typeof)            {                monitor.wait (   program) (typeof); Releases the lock on the object and blocks the current thread until it acquires the lock again.                Console.WriteLine (Thread.CurrentThread.Name + "Start executing other logic");            }          }        void Getshow ()        {            Lock (typeof (program))            {                Console.WriteLine (subthread. name+ "Thread execution Complete");                Monitor.pulse (typeof (Program));  Notifies a thread in the waiting queue of a change in the lock object state.            }        }    }



"Multithreading-Thread 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.