. NET Foundation Supplements (7) Multithreaded Development Fundamentals 4

Source: Internet
Author: User
Tags instance method mutex semaphore

I. Thread synchronization in multithreaded programming

The Lock keyword in 1.c#

The lock keyword may be the most common way we encounter the need for thread synchronization, but lock is just a syntactic sugar, so why do you say that, slowly?

(1) The equivalent code of lock is actually the Enter and exit two methods of the Monitor class

Private Object locker = new Object ();    public void works ()    {          lock (locker)          {              //Do some work that requires thread synchronization          }     }
Private Object locker = new Object (); public void work () { //avoid direct use of private member locker (direct use may cause thread insecurity) Object temp = locker; Monitor.Enter (temp); Try { //Do some work that requires thread synchronization } finally { monitor.exit (temp); } }

(2) function and use of System.Threading.Monitor type

The Enter and exit methods of the monitor type are used to implement synchronization of entry and exit objects, and when the Enter method is called, the synchronization index of the object is checked, and. NET will be responsible for a series of subsequent work to ensure thread synchronization at object access, while the call to the exit method guarantees that the current thread frees the object's synchronization block.

The

example demonstrates how to use the Lock keyword to implement thread synchronization:

Class Program {static void Main (string[] args) {//Multithreading test static method synchronization Console.WriteLine            ("Start testing the synchronization of static methods:");                for (int i = 0; i < 5; i++) {Thread thread = new Thread (lock.staticincrement); Thread.            Start ();            }//Here waits for thread execution to end Thread.Sleep (5 * 1000);            Console.WriteLine ("-------------------------------");            The synchronous Console.WriteLine of the Multithreaded Test instance method ("Start the synchronization of Test instance methods:");            Lock L = new lock ();                for (int i = 0; i < 6; i++) {Thread thread = new Thread (l.instanceincrement); Thread.            Start ();        } console.readkey ();        }} public class Lock {//static method synchronous lock private static Object Staticlocker = new Object ();        Instance method synchronous Lock Private Object Instancelocker = new Object ();        Member variable private static int staticnumber = 0; private int instanceNumber = 0;                Test static method synchronization public static void Staticincrement (object state) {Lock (Staticlocker) {                Console.WriteLine ("Current Thread id:{0}", Thread.CurrentThread.ManagedThreadId.ToString ());                Console.WriteLine (The value of "Staticnumber: {0}", staticnumber.tostring ());                Here you can create the opportunity for parallel execution of threads to check the function of synchronization thread.sleep (200);                staticnumber++;            Console.WriteLine ("Staticnumber after self-increment: {0}", staticnumber.tostring ()); }}//The synchronization of the test instance method public void Instanceincrement (object state) {Lock (Instancelocker                {Console.WriteLine ("Current Thread id:{0}", Thread.CurrentThread.ManagedThreadId.ToString ());                Console.WriteLine (The value of "Instancenumber: {0}", instancenumber.tostring ());                Here you can create the opportunity for parallel execution of threads to check the function of synchronization thread.sleep (200);                instancenumber++; Console.WriteLine ("Instancenumber fromAdded to: {0} ", instancenumber.tostring ()); }        }    }

  

PS: You should completely avoid using the This object and the current type object as synchronization objects, but instead define a private synchronization object in the type.

You should also use lock instead of the monitor type, which effectively reduces the synchronization block from being freed.

2. What is a mutex? What is the difference between a mutex and monitor two types of functionality?

(1) What is a mutex?

In the operating system, mutexes (mutexes) mean that some code fragments allow only one thread to enter at any time. For example, a chess is in progress, allowing only one player to Lazi on the board at any given time, which is basically consistent with the concept of thread synchronization.

(2). NET Mutex

The mutex class is a type of mutex that is encapsulated in. NET, similar to a mutex and semaphore (semaphore). The following sample code shows the use of the Mutext type

Class Program {const string testfile = "C:\\testmutex.txt";  <summary>///This mutex guarantees that all processes can be synchronized///</summary> static Mutex mutex = new Mutex (false,        "Testmutex");            static void Main (string[] args) {//Set aside time to start other processes Thread.Sleep (3000);            DoWork (); Mutex.            Close ();        Console.readkey ();            }///<summary>///To write continuous content to the file///</summary> static void DoWork () {            Long D1 = DateTime.Now.Ticks; Mutex.            WaitOne ();            Long D2 = DateTime.Now.Ticks; Console.WriteLine ("After {0} ticks after process {1} obtains the mutex, enters the critical section code.") ", (D2-D1). ToString (), process.getcurrentprocess ().            Id.tostring ()); try {if (!                    File.exists (testfile)) {FileStream fs = File.create (testfile); Fs.                Dispose (); } for (int i = 0; i < 5; i++)                {//each time the file is closed and re-opened//determined to have a mutex to synchronize, not an IO mechanism using                    (FileStream fs = File.Open (Testfile, Filemode.append)) {String content = "Process" + process.getcurrentprocess ().                        Id.tostring () + "": "+ i.tostring () +" \ r \ n ";                        byte[] data = Encoding.Default.GetBytes (content); Fs. Write (data, 0, data.                    Length);                }//simulation did other work thread.sleep (300); }} finally {mutex.            ReleaseMutex ();  }        }    }

Simulating multiple users, executing the above code, is the result of the execution on my computer:

Now open the TestMutext.txt file in the C drive directory and you will see the results as shown:

(3) The difference between a mutex and a monitor

Although both are used to synchronize the function, but the implementation method is different, the most significant of the two differences are as follows:

①mutex uses the kernel object of the operating system, and the monitor type synchronization mechanism is implemented entirely under the. NET Framework, which results in a much lower efficiency of the mutext type than the monitor type ;

The ② monitor type can only synchronize threads in the same application domain, while the mutex type spans application domains and processes .

. NET Foundation Supplements (7) Multithreaded Development Fundamentals 4

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.