From 0 self-taught c#12--thread synchronization solution Rollup and pros and cons

Source: Internet
Author: User
Tags semaphore thread stop
First, be sure: Microsoft's Framework Class Library (FCL) ensures that all static methods are thread-safe.

The FCL does not guarantee that the instance method is thread safe. Because if all add locks, it will cause a huge loss of performance. In addition, if each instance method needs to acquire and release a lock, it will in fact result in the end at any given moment when only one thread of your application is running, which has an obvious impact on performance.

The following describes the primitive thread synchronization constructs.

Primitive: Refers to the simplest construct that can be used in code. There are two primitive constructs: User mode (user-mode) and kernel mode (Kernel-mode).

User mode

A special CPU instruction is used to coordinate threads.

Technology: Volatile keyword, interlocked class (interlock), spinlock (Spin lock)

The common lock ①:volatile keyword indicates that a field can be modified by multiple threads that are concurrently executing. Fields declared as volatile are not limited by compiler optimizations (presumably accessed by a single thread). This ensures that the field is present at any time with the most recent value.

Interlocked class: Provides atomic operations for variables shared by multiple threads. Atomic operations are operations that are not interrupted by the thread-scheduling mechanism, which, once started, runs until the end without any context switch (switching to another thread).

The common lock ②:spinlock structure is a low-level mutex synchronization primitive that rotates when it waits for a lock to be acquired. On multi-core computers, SpinLock performance will be higher than other types of locks when the wait time is expected to be short and race conditions are rare. Even if the SpinLock does not acquire a lock, it also produces a thread's time slice. It does this to avoid thread-priority inversion and to enable the garbage collector to continue executing. When using SpinLock, make sure that no thread holds the lock for longer than a very short period of time, and that any thread will not block when holding the lock.

Advantages:

You should use primitive user-mode constructs whenever possible, and they are significantly faster than kernel-mode constructs.

Reconcile threads that occur in hardware (so quickly).

However, the Microsoft Windows operating system never detects that a thread is blocked on the construction of the primitive user mode.

Because the thread pool that is blocked in user-mode primitive constructs is never considered blocked, the thread pool does not create new threads to replace this temporary thread.

These CPU instructions only block the thread for a fairly short time.

Disadvantages:

Only the Windows operating system kernel can stop a thread from running (preventing it from wasting CPU time).

Threads running in user mode may be preempted by the system, but the threads are dispatched again at the fastest speed.

Threads that want to get resources but are temporarily unavailable will always "spin" in user mode, which can waste a lot of CPU time. Threads are always running on one CPU, which we call "live locks" (livelock).

Instance:

Using system;using System.threading;public class worker{//This method is called when the thread is started.        public void DoWork () {while (!_shouldstop) {Console.WriteLine ("Worker thread:working ...");    } Console.WriteLine ("Worker thread:terminating gracefully.");    } public void RequestStop () {_shouldstop = true;    }//Keyword volatile is used as a hint to the compiler, this data//member are accessed by multiple threads. private volatile bool _shouldstop;} public class workerthreadexample{static void Main () {//Create the worker thread object.        This does does not start the thread.        Worker Workerobject = new Worker ();        Thread workerthread = new Thread (workerobject.dowork);        Start the worker thread.        Workerthread.start ();        Console.WriteLine ("Main thread:starting worker thread ...");        Loop until the worker thread activates. while (!workerthread.isalive) ;        Put the main thread to sleep for 1 millisecond to//allow the worker thread to do some work.        Thread.Sleep (1);        Request that the worker thread stop itself.        Workerobject.requeststop ();        Use the Thread.Join method to block the current thread//until the object ' s thread terminates.        Workerthread.join ();    Console.WriteLine ("Main Thread:worker thread has terminated."); }//Sample output://Main thread:starting worker thread ...//worker thread:working ...//worker Thread:w Orking ...//worker thread:working ...//worker thread:working ...//worker thread:working .../worker thr    Ead:working.//Worker thread:terminating gracefully. Main Thread:worker thread has terminated.}

Kernel mode

Provided by the Windows operating system itself. They require that functions that have an operating system kernel implementation be called in the application's thread.

Technology: EventWaitHandle (Event), Semaphore (semaphore), mutex (mutex)

System.Object System.MarshalByRefObject System.Threading.WaitHandle System.Threading.EventWaitHandle System. Threading.mutex System.Threading.Semaphore

The common lock ③:mutex class is a Win32 constructed wrapper that can be marshaled across application domain boundaries, can be used for multiple waits, and can be used to synchronize threads in different processes.

Advantages:

When a thread acquires a resource owned by another thread through a kernel-mode construct, Windows blocks the thread to avoid wasting CPU time. When a resource becomes available, Windows resumes the thread and allows it to access the resource. It does not occupy a CPU "spin".

Enables synchronization between native and managed threads.

Threads that run in different processes on the same machine can be synchronized.

Security settings can be applied to prevent unauthorized accounts from accessing them.

Threads can be blocked until all kernel-mode constructs are available for collaboration, or until any kernel-mode constructs in the collection are available.

A thread that is blocked on a kernel-mode construct can specify a time-out value: The thread can unblock and perform other tasks if the desired resource is not accessed within the specified period.

Disadvantages:

Switching threads from user mode to kernel mode (or vice versa) incurs a significant performance penalty, which is why you should avoid using kernel constructs. In addition, threads are blocked, causing "deadlock" (deadlock).

Deadlock is always due to a live lock, because a live lock is a waste of CPU time, there is a waste of memory (line stacks, etc.), and deadlock only waste memory.

Mixed construction

Combines the advantages of both. In the absence of competition, fast and does not block (just like user mode). In a competitive situation, expect it to be blocked by the operating system kernel.

Technology: ManualResetEventSlim class, Semaphoreslim class, Monitor class, lock class, ReaderWriterLockSlim class, Countdownevent class, Barrier class, double check lock.

Common lock ④:monitor are generally preferable because the monitor is designed specifically for the. NET Framework, so it makes better use of resources than mutexes. Although a mutex is more powerful than a monitor, it requires an interoperability transformation that consumes computing resources more than the monitoring class.

Common lock ⑤: using the Lock (C #) or SyncLock (Visual Basic) keyword is the package for monitor. It is generally preferable to use the Monitor class directly, on the one hand because lock or SyncLock is more concise, on the other hand, because lock or SyncLock ensures that the underlying monitor can be released even if the protected code throws an exception.

Common lock ⑥:readerwriterlock Locks, in some cases, you might want to lock resources only when writing data, allowing multiple clients to read data at the same time when data is not being updated. The ReaderWriterLock class enforces its exclusive access to the resource when it modifies the resource, but allows non-exclusive access while reading the resource. The Readerwriter lock can be used instead of an exclusive lock. When you use exclusive locks, these threads wait even if other threads do not need to update the data.

Double check Lock

Common lock ⑦: double check lock mode (also known as "Double check lock Optimization", "lock hint") is a software design pattern used to reduce the cost of contention and synchronization in concurrent systems.

Double-check locking mode first verifies the locking condition (first check), and only the lock logic is really locked and the condition is verified again (the second check).

It is typically used to reduce lock-in overhead, especially for "lazy initialization" of singleton patterns in multithreaded environments. Lazy initialization means that its value is not initialized until it is first accessed.

public sealed class Singleton {private static volatile Singleton instance = null;        private static Object syncRoot = new Object ();        private static int count = 100; Private Singleton () {} public static Singleton Instance {get {if ' (in stance = = null) {lock (SyncRoot) {if (Instan                    CE = = null) instance = new Singleton ();            }} return instance;                }} public static Singleton Getsingleton () {if (instance = = null) {                        Lock (SyncRoot) {if (instance = = null) {                    Instance = new Singleton ();        }}} return instance; } public override stringToString () {lock (syncRoot) {int buf =--count;                Thread.Sleep (20); return buf + "_" + count.            ToString (); }}}static void Main (string[] args) {task<string>[] tasks = new TASK&LT;STRING&GT;[10]            ;            Stopwatch watch = new Stopwatch ();            Object syncRoot = new Object (); Watch.            Start (); for (int i = 0; i < tasks. Length; i++) {Tasks[i] = task.factory.startnew<string> (() = (Singleton.getsingleton ().                                ToString ())); } task.waitall (tasks, 5000);//Set timeout 5s watch.            Stop (); Console.WriteLine ("Tasks running need" + watch.)            Elapsedmilliseconds + "Ms." + "\ n"); for (int i = 0; i < tasks. Length; i++) {//Timeout processing if (Tasks[i]. Status! = taskstatus.rantocompletion) {ConsOle.                WriteLine ("Task {0} error!", i + 1);  } else {//save result Console.WriteLine ("Tick ID is") + Tasks[i].                    Result);                Console.WriteLine (); }} for (int i = 0; i < 3; i++) {Console.WriteLine ("Main thread does wor                K! ");            Thread.Sleep (200);        } console.readkey (); }

Output:

Tasks running need 298 Ms.  Tick ID is 96_96tick ID are 99_99tick ID is 97_97tick ID is 98_98tick ID is 95_95tick ID is 94_94tick ID is 93_93tick ID is 92_92tick ID is 91_91tick ID was 90_90main thread do work! Main thread do work! Main thread do work!

The above is from 0 self-learning c#12--thread Synchronization Solution summary and the pros and cons of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.