. NET synchronous and asynchronous Mutex (12),. net synchronous mutex

Source: Internet
Author: User

. NET synchronous and asynchronous Mutex (12),. net synchronous mutex

This essay continued: a set of. NET synchronization and asynchronous thread security (11)

This article and the next two articles will introduce the last major knowledge point of the. NET synchronization and Asynchronous Series: WaitHandle family.

Abstract base class: WaitHandle, three subclasses: EventWaitHandle (Event Notification), Mutex (Process Synchronization lock), Semaphone (semaphore), and two grandchildren: System. threading. autoResetEvent, System. threading. manualResetEvent is a subclass of EventWaitHandle.

 

I. abstract base class WaitHandle
[ComVisibleAttribute(true)]public abstract class WaitHandle : MarshalByRefObject, IDisposable

Through the above information, we can know that WaitHandle inherits from MarshalByRefObject and implements the IDisposable interface.

You may not be very familiar with MarshalByRefObject, but you will certainly use many of its sub-classes. Let's unveil its true nature.

In MSND, MarshalByRefObject is described as follows:

An application domain is the partition where one or more applications reside in an operating system process. Objects in the same application domain can communicate directly. There are two communication methods for objects in different application domains: one is to transmit object copies across application domain boundaries, and the other is to exchange messages using a proxy.MarshalByRefObjectIt is the base class of an object that uses proxy to exchange messages to communicate across application domain boundaries.

You may be even more confused here. I used it? Used its subclass? Yes, it's just a subclass of it, and there are a lot more.

For example, the Brush, Image, Pen, and Font of the System. Drawing namespace, and a Stream under the System. IO namespace that you are more familiar.

Extended reading: ExploitationMarshalByRefObjectImplement AOP.

Here, we only need to know That WaitHandle can communicate across application domains.

 

Ii. Mutex (Process Synchronization lock) 1. MSDN defines Mutex as a synchronization primitive between processes, that is, the concept of lock.

In contrast, Monitor is usually used for communication between threads in the application domain. In fact, if the object used for lock is derived from financialbyrefobject, Monitor can also provide locking in multiple application domains.

Because Mutex needs to call operating system resources, the execution overhead is much greater than that of Monitor. Therefore, if you only need to synchronize operations between threads in the application, Monitor/lock should be the first choice.

2. Mutex usage
  • WaitOne ()/WaitOne (TimeSpan, Boolean) and several reloads: Request ownership. The call will be blocked until the current mutex receives the signal or the optional timeout interval is reached, these methods do not need to provide the locked object as an additional parameter.
    • You can use WaitHandle. WaitOne to request the mutex of ownership. The call thread is blocked until one of the following conditions occurs ︰
    • The mutex sends a signal to indicate that it does not own the mutex. In this case, the WaitOne method returnsTrue, The call thread's mutex ownership, and access resources protected by mutex. When the thread accesses the resource, the ReleaseMutex method must be called to release the ownership of the mutex.

    • Has a method for the specified Timeout interval WaitOne in the callMillisecondsTimeoutOrTimeoutThe parameter has passed. In this case, the WaitOne method returnsFalseIn this case, the thread does not obtain the ownership of the mutex.

  • ReleaseMutex (): Release the current Mutex once. Note: This is emphasized once, because threads with mutex can repeatedly call the WaitOne series functions without blocking them from execution; this is the same as the press Enter ()/Exit () of Monitor () it can be called repeatedly after obtaining the object lock. The number of Mutex calls is saved by the Common Language Runtime Library (CLR). Each WaitOne () is counted + 1, and each ReleaseMutex () is counted-1, as long as the Count is not 0, other Mutex wait persons will think that the Mutex is not released, and there is no way to obtain the Mutex. In addition, like Monitor. Exit (), only the Mutex owner can RleaseMutex (). Otherwise, an exception is thrown.
  • If the thread terminates when it has a mutex, we call it Abandoned ). In MSDN, Microsoft warned that this was a "serious" programming error. This means that after the owner of mutex obtains the ownership, the number of WaitOne () and RelaseMutex () is not equal, and the caller does not stop it responsibly, the resources that mutex is protecting may be in an inconsistent state. Actually, this is nothing more than reminding youRemember to use Mutex in the try/finally structure.
3, Global and local Mutex

If Mutex is used in an application domain, it is better to use Monitor/lock directly because Mutex requires more overhead and execution is slow. However, after all, Mutex is not a Monitor/lock. It is designed to be used for inter-process synchronization. The Mutex used for inter-process communication is called Global Mutex, And the Mutex used for intra-application domain communication is called local Mutex.

Global Mutex and local Mutex construct different instances through constructor. Let's take a look at the Mutex constructor. There are five in total. Let's pick two representative ones:

  • Mutex (): Mutex obtained by using a constructor without parameters has no name, and data cannot be shared among processes in the form of variables. Therefore, Mutex with no name is also calledLocal Mutex. In addition, the Creator does not have ownership of the created Mutex instance and still needs to call WaitOne () to request ownership.
  • Mutex (Boolean initiallyOwned, String name, out Booldan createdNew, MutexSecurity): The first bool parameter indicates whether the initialized instance has the Mutex ownership. The second string type specifies a name for the Mutex. If the string is null or empty, it is equivalent to creating a Mutex without a name. the Mutex with the name belongs to the global Mutex. the third bool parameter returns True if the mutex has been initialized and False if the mutex already exists. the last parameter is used for Mutex access security control.
4. Purpose

Mutex is a synchronization primitive between processes, so it can be used to controlApplication Single Instance:

/// <Summary> /// run on a single instance /// </summary> /// <returns> the true application has been started, false indicates no </returns> public bool SingleRun (ref System. threading. mutex mutex) {mutex = new System. threading. mutex (false, "WINDOWS"); if (! Mutex. WaitOne (0, false) {mutex. Close (); mutex = null;} if (mutex = null) {return true;} return false ;}Single Process instance

 

 

To be continued, next article: EventWaitHandle (Event Notification)

Appendix, Demo: http://files.cnblogs.com/files/08shiyan/ParallelDemo.zip

See more: Casual guide: synchronous and asynchronous

 

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.