Locking system in multi-threading (iii)-waithandle, AutoResetEvent, ManualResetEvent

Source: Internet
Author: User
Tags semaphore

Introduced

This chapter mainly describes thread synchronization, events, and semaphores based on kernel-mode constructs.

Directory

One: Theory

Two: WaitHandle

Three: AutoResetEvent

Four: ManualResetEvent

V: summary

One: Theory

We know that thread synchronization can be divided into user-mode constructs and kernel-mode constructs.

Kernel-mode construction: The kernel object is used by the Windows system itself to dispatch assistance. a Kernel object is a block of memory in the system address space that is created and maintained by the system.

kernel objects are owned by the kernel and are not owned by the process, so different processes can access the same kernel objects, such as processes, threads, jobs, events , files, semaphores , mutexes, etc. are kernel objects.

and semaphores, mutexes, events are kernel objects that Windows specifically uses to help us thread synchronization.

For thread synchronization operations, the kernel object has only 2 states, triggering (terminating, true), not triggering (non-terminating, false). No dispatch is triggered and the trigger can be dispatched.

User-mode construction: is a special CPU instructions to coordinate threads, the above-said volatile implementation is one,interlocked is also. It can also be called non-blocking thread synchronization .

Two: WaitHandle

In Windows programming, when we create a kernel object through the API, we return a handle, which is the index of each process handle table, and then we can get pointers, masks, markers, etc. of the kernel object.

The WaitHandle abstract base class function is to wrap a handle to a Windows kernel object . Let's take a look at one of the WaitOne's function sources (slightly streamlined).

         Public Virtual BOOLWaitOne (TimeSpan timeout) {returnWaitOne (Timeout,false); } [System.Security.SecuritySafeCritical]//auto-generated[SuppressMessage ("microsoft.concurrency","CA8001", justification ="reviewed for thread-safety.")]        Private BOOLWaitOne (LongTimeoutBOOLexitcontext) {            returnInternalwaitone (Safewaithandle, timeout, hasthreadaffinity, exitcontext); } [System.Security.SecurityCritical]        Internal Static BOOLInternalwaitone (SafeHandle Waitablesafehandle,LongMillisecondstimeout,BOOLHasthreadaffinity,BOOLexitcontext)            {Contract.endcontractblock (); intret = Waitonenative (Waitablesafehandle, (UINT) millisecondstimeout, hasthreadaffinity, exitcontext); if(ret = =wait_abandoned)            {throwabandonedmutexexception (); }            return(Ret! =waittimeout); }//Call Win32 WaitForSingleObjectEx [System.Security.SecurityCritical][Resourceexposure (Resourcescope.none)] [MethodImplAttribute (Methodimploptions.internalcall)] Private Static extern intWaitonenative (SafeHandle Waitablesafehandle,UINTMillisecondstimeout,BOOLHasthreadaffinity,BOOLexitcontext);

WaitAll and WaitAny call Win32 in the WAITFORMULTIPLEOBJECTSEX function.

Signalandwaitone calls Win32 in the SIGNALANDWAIT function.

The call API with ex is set to timeout. If we do not pass in C #, the default is-1 means wait indefinitely.

Where the Safewaithandle field contains a handle to the Win32 kernel object.

Understand the WaitHandle others are good, let's look at its derived types.

WaitHandle
|--eventwaithandle event constructs.
|--autoresetevent
|--manualresetevent
|--semaphore Semaphore construction.
|--mutex

One of the semaphore and the first chapter of the mutex has been said, below to look at the other.

Three: AutoResetEvent

Use an example below, with a simple comment. As to the description, try to be close to the system's own terminology.

  Static voidMain (string[] args) {            //AutoResetEvent Example//AutoResetEvent notifies the waiting thread that an event has occurred. AutoResetEvent Waithandler =NewAutoResetEvent (false);//false is non-terminating and not triggered.             NewThread (() ={waithandler.waitone (); //blocks the current thread and waits for the underlying kernel object to receive a signal. Console.WriteLine ("receive a signal and start processing. "); }).            Start (); NewThread (() ={Thread.Sleep ( -); Console.WriteLine ("Send Signal");    Waithandler.set (); //sends a signal to the kernel object.  Sets the event object to be non-terminating, false, and unblocked.             }).            Start (); //waithandler.close ();//disposes the handle resource. //Waithandler.reset (); //Manualsets the event to a non-terminating state, false, and thread blocking. Console.ReadLine (); }

WaitOne blocking threads, non-spin.

Set () Sets the event status to false after a signal is emitted. This should be a 2-step operation, AutoResetEvent.Set () function, to 2 steps together automatically, very convenient.

Four: ManualResetEvent

This is basically the same as above, and literally requires a manual reset, let's take a look at the example.

ManualResetEvent Manualwaithandler =NewManualResetEvent (false);//false is non-terminating and not triggered.             NewThread (() ={manualwaithandler.waitone (); //blocks the current thread object and waits for a signal. Console.WriteLine ("receive a signal and start processing. ");  Manualwaithandler.reset (); //Manualsets the event object state to a non-terminating state, false. Manualwaithandler.waitone ();//here the direct blocking wait is invalid because the event object is still true and reset must be manually adjusted. Console.WriteLine ("The second time receives the signal, starts the processing. "); }).            Start (); NewThread (() ={Thread.Sleep ( -); Console.WriteLine ("Send Signal");    Manualwaithandler.set (); //send an OK signal to the event object ... Thread.Sleep ( -); Console.WriteLine ("second Signal,");            Manualwaithandler.set (); }).            Start (); Console.ReadLine ();

The 2 difference is very small, is actually the system API distinction, is not NET class library implementation.

In the Win32native class, I can see that the KERNEL32 API has this parameter ismanualreset.

[DllImport (KERNEL32, setlasterror=true, CharSet=CharSet.Auto, bestfitmapping=false)]         // Machine or none based on the value of "name"        Internal Static extern BOOL bool initialstate, String name);
V: summary

The synchronization step based on kernel-mode construction is the kernel-mode code, the user-mode code, managed code, and vice versa. This way down, performance is certainly not there. Everyone pay attention to the distinction.

User-mode construction is the use of CPU special instructions for atomic operations.

User-mode code,. Refers to the layer where managed code calls the Win32 code, after which the kernel-mode code is tuned.

Reference Resources

1:CLR via C #

2:windows Core Programming version Fifth

If there are errors, please point out the correction. For your help, please recommend the next n (* ≧▽≦ *) n.

Mr. Mushroom

Source: http://www.cnblogs.com/mushroom/p/4198429.html

Locking system in multi-threading (iii)-waithandle, AutoResetEvent, ManualResetEvent

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.