In a nutshell:

Source: Internet
Author: User
In a nutshell:
-Monitor. Enter/exit and mutexes are commonly used for protecting objects
From being used by two threads at the same time. Every thread acquires
Mutex (resp. enters the monitor) before it uses the object, and no other
Thread will be allowed to do the same until the mutex is released (resp.
Monitor is exited); the monitor methods are faster and use less memory,
Mutexes can be shared using SS Processes
-The lock statement internally uses the monitor. Enter/exit Methods
-Monitor. Pulse/Wait are used for sending events to other threads;
Monitor. Wait will wait until "pulse" is called by another thread. They are
Usually used to wake up some idling thread. (autoresetevent/manualresetevent
Serve similar purposes)
-Semaphores are much like mutexes, however they permit more than one access
At a time (e.g. It you want at most 3 of your threads accessing a database
At a time)

I hope this short intro helps a little; Jon Skeet has an excellent article
On multithreading, you can use Google to find it.

Overview of synchronization primitives . NET framework 4 Other Versions
    • Visual Studio 2008
    • . NET Framework 3.0
    • Visual Studio 2005
    • Silverlight

The. NET Framework provides a range of synchronization primitives for controlling the interactions of threads and avoiding race conditions. These can be roughly divided into three categories: locking, signaling, and interlocked operations.

The categories are not tidy nor clearly defined: Some synchronization mechanic ISMs have characteristics of multiple categories; events that release a single thread at a time are functionally like locks; the release of any lock can be thought of as a signal; and interlocked operations can be used to construct locks. however, the categories are still useful.

It is important to remember that thread synchronization is cooperative. If even one thread bypasses a synchronization mechanic and accesses the protected resource directly, that synchronization mechanic cannot be valid.

This overview contains the following sections:

    • Locking

    • Signaling

    • Lightweight synchronization types

    • Spinwait

    • Interlocked operations

Locking

Locks give control of a resource to one thread at a time, or to a specified number of threads. A thread that requests an exclusive lock when the lock is in use blocks until the lock becomes available.

Exclusive locks

The simplest form of locking is the C #LockStatement (SynclockIn Visual Basic), which controls access to a block of Code. Such a block is frequently referred to as a critical section.LockStatement is implemented by usingEnterAndExitMethods ofMonitorClass, and it usesTry... Catch... FinallyTo ensure that the lock is released.

In general, usingLockStatement to protect small blocks of code, never spanning more than a single method, is the best way to useMonitorClass. Although powerful,MonitorClass is prone to orphan locks and deadlocks.

Monitor class

TheMonitorClass provides additional functionality, which can be used in conjunction withLockStatement:

    • TheTryenterMethod allows a thread that is blocked waiting for the resource to give up after a specified interval. It returns a Boolean value indicating success or failure, which can be used to detect and avoid potential deadlocks.

    • TheWaitMethod is called by a thread in a critical section. It gives up control of the resource and blocks until the resource is available again.

    • ThePulseAndPulseallMethods allow a thread that is about to release the lock or to callWaitTo put one or more threads into the ready queue, so that they can acquire the lock.

Timeouts onWaitMethod overloads allow waiting threads to escape to the ready queue.

TheMonitorClass can provide locking in multiple application domains if the object used for the lock derives fromMarshalbyrefobject.

MonitorHas thread affinity. That is, a thread that entered the monitor must exit by callingExitOrWait.

TheMonitorClass is not instantiable. Its methods are static (SharedIn Visual Basic), and act on an instantiable Lock Object.

For a conceptual overview, seeMonitors.

Mutex class

Threads requestMutexBy calling an overload of itsWaitoneMethod. Overloads with Timeouts are provided, to allow threads to give up the wait. UnlikeMonitorClass, A mutex can be either local or global. global mutexes, also called named mutexes, are visible throughout the operating system, and can be used to synchronize threads in multiple application domains or processes. local mutexes derive fromMarshalbyrefobject, And can be used using SS application domain boundaries.

In addition,MutexDerives fromWaithandle, Which means that it can be used with the Signaling Mechanisms providedWaithandle, Such asWaitall,Waitany, AndSignalandwaitMethods.

LikeMonitor,MutexHas thread affinity. UnlikeMonitor,MutexIs an instantiable object.

For a conceptual overview, seeMutexes.

Spinlock class

Starting with the. NET Framework Version 4, you can useSpinlockClass when the overhead requiredMonitorDegrades performance. WhenSpinlockEncounters a locked critical section, it simply spins in a loop until the lock becomes available. if the lock is held for a very short time, spinning can provide better performance than blocking. however, if the lock is held for more than a few tens of cycles,SpinlockPerforms just as wellMonitor, But will use more CPU cycles and thus can degrade the performance of other threads or processes.

Other locks

Locks need not be exclusive. It is often useful to allow a limited number of threads concurrent access to a resource. semaphores and reader-writer locks are designed to control this kind of pooled resource access.

Readerwriterlock class

TheReaderwriterlockslimClass addresses the case where a thread that changes data, the writer, must have exclusive access to a resource. when the writer is not active, any number of readers can access the resource (for example, by callingEnterreadlockMethod). When a thread requests exclusive access, (for example, by callingEnterwritelockMethod), subsequent reader requests block until all existing readers have exited the lock, and the writer has entered and exited the lock.

ReaderwriterlockslimHas thread affinity.

For a conceptual overview, seeReader-writer locks.

Semaphore class

TheSemaphoreClass allows a specified number of threads to access a resource. Additional threads requesting the resource block until a thread releases the semaphore.

LikeMutexClass,SemaphoreDerives fromWaithandle. Also likeMutex,SemaphoreCan be either local or global. It can be used using SS application domain boundaries.

UnlikeMonitor,Mutex, AndReaderwriterlock,SemaphoreDoes not have thread affinity. This means it can be used in scenarios where one thread acquires the semaphore and another releases it.

For a conceptual overview, seeSemaphore and semaphoreslim.

System. threading.SemaphoreslimIs a lightweight semaphore for synchronization within a single process boundary.

Back to Top

Signaling

The simplest way to wait for a signal from another thread is to callJoinMethod, which blocks until the other thread completes.JoinHas two overloads that allow the blocked thread to break out of the wait after a specified interval has elapsed.

Wait handles provide a much richer set of waiting and signaling capabilities.

Wait handles

Wait handles derive fromWaithandleClass, which in turn derives fromMarshalbyrefobject. Thus, wait handles can be used to synchronize the activities of threads internal SS application domain boundaries.

Threads block on wait handles by calling the instance methodWaitoneOr one of the static methodsWaitall,Waitany, OrSignalandwait. How they are released depends on which method was called, and on the kind of wait handles.

For a conceptual overview, seeWait handles.

Event wait handles

Event wait handles includeEventwaithandleClass and Its Derived classes,AutoreseteventAndManualresetevent. Threads are released from an event wait handle when the event wait handle is signaled by calling itsSetMethod or by usingSignalandwaitMethod.

Event wait handles either reset themselves automatically, like a turnstile that allows only one thread through each time it is signaled, or must be reset manually, like a gate that is closed until signaled and then open until someone closes it. as their names imply,AutoreseteventAndManualreseteventRepresent the former and latter, respectively.System. threading.ManualreseteventslimIs a lightweight event for synchronization within a single process boundary.

AnEventwaithandleCan represent either type of event, and can be either local or global. The Derived classesAutoreseteventAndManualreseteventAre always local.

Event wait handles do not have thread affinity. Any thread can signal an event wait handle.

For a conceptual overview, seeEventwaithandle, autoresetevent, countdownevent, and manualresetevent.

Mutex and semaphore classes

BecauseMutexAndSemaphoreClasses derive fromWaithandle, They can be used with the static methodsWaithandle. For example, a thread can useWaitallMethod to wait until all three of the following are true:EventwaithandleIs signaled,MutexIs released, andSemaphoreIs released. Similarly, a thread can useWaitanyMethod To wait until any one of those conditions is true.

ForMutexOrSemaphore, Being signaled means being released. If either type is used as the first argument ofSignalandwaitMethod, it is released. In the case ofMutex, Which has thread affinity, an exception is thrown if the calling thread does not own the mutex. As noted previusly, semaphores do not have thread affinity.

Barrier

TheBarrierClass provides a way to define ically synchronize multiple threads so that they all block at the same point and wait for all other threads to complete. A barrier is useful when one or more threads require the results of another thread before continuing to the next phase of an algorithm. for more information, seeBarrier (. NET Framework).

Back to Top

Lightweight synchronization types

Starting with. NET framework 4, you can use synchronization primitives that provide fast performance by avoiding expensive reliance on Win32 kernel objects such as wait handles whenever possible. in general, you should use these types when wait times are short and only when the original synchronization types have been tried and found to be unsatisfactory. the lightweight types cannot be used in scenarios that require cross-process communication.

    • System. threading.SemaphoreslimIs a lightweight versionSystem. threading.Semaphore.

    • System. threading.ManualreseteventslimIs a lightweight versionSystem. threading.Manualresetevent.

    • System. threading.CountdowneventRepresents an event that becomes signaled when its count is zero.

    • System. threading.BarrierEnables multiple threads to synchronize with one another without requiring control by a master thread. A barrier prevents each thread from continuing until all threads have reached a specified point.

Back to Top

Spinwait

Starting with the. NET Framework 4, you can useSystem. threading.SpinwaitStructure when a thread has to wait for an event to be signaled or a condition to be met, but when the actual wait time is expected to be less than the waiting time required by using a wait handle or by otherwise blocking the current thread. by usingSpinwait, You can specify a short period of time to spin while waiting, and then yield (for example, by waiting or sleeping) only if the condition was not met in the specified time.

Back to Top

Interlocked operations

Interlocked operations are simple atomic operations saved med on a memory location by static methods ofInterlockedClass. Those atomic operations include addition, increment and decrement, exchange, conditional exchange depending on a comparison, and read operations for 64-bit values on 32-bit platforms.

Note

The guarantee of Atomicity is limited to individual operations; when multiple operations must be passed med as a unit, a more coarse-grained synchronization mechanic must be used.

Although none of these operations are locks or signals, they can be used to construct locks and signals. Because they are native to the Windows operating system, interlocked operations are extremely fast.

Interlocked operations can be used with volatile memory guarantees to write applications that exhibit powerful non-blocking concurrency. however, they require sophisticated, low-level programming, so for most purposes, simple locks are a better choice.

For a conceptual overview, seeInterlocked operations.

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.