国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development C#.Net Tutorial Self-study C#12 from 0--A summary of thread synchronization solutions and their advantages and disadvantages

Self-study C#12 from 0--A summary of thread synchronization solutions and their advantages and disadvantages

Feb 04, 2017 am 11:11 AM

First of all, one thing is certain: Microsoft's Framework Class Library (FCL) ensures that all static methods are thread-safe.

FCL does not guarantee that instance methods are thread-safe. Because if all locks are added, it will cause a huge loss of performance. In addition, if each instance method needs to acquire and release a lock, in fact, you will end up with only one thread running in your application at any given moment, which has an obvious impact on performance.

The following introduces the primitive thread synchronization construct.

Primitive: refers to the simplest construct that can be used in code. There are two primitive constructs: user-mode and kernel-mode.

User mode

Special CPU instructions are used to coordinate threads.

Technology: volatile keyword, Interlocked class (interlock), spinlock (spin lock)

Common lock ①: volatile keyword indicates that a field can be modified by multiple threads executing simultaneously . Fields declared volatile are not subject to compiler optimizations (assuming access by a single thread). This ensures that the field presents the latest value at any time.

Interlocked class: Provides atomic operations for variables shared by multiple threads. . The so-called atomic operation refers to an operation that will not be interrupted by the thread scheduling mechanism; once this operation starts, it will run until the end without any context switch (switch to another thread) in the middle.

Common lock ②: The SpinLock structure is a low-level mutex synchronization primitive that rotates while waiting to acquire the lock. On multi-core computers, SpinLock will perform better than other lock types when wait times are expected to be short and contention conditions are rare. Even if SpinLock does not acquire the lock, it generates the 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 more than a very short period of time, and that no thread blocks while holding the lock.

Advantages:

Primitive user-mode constructs should be used whenever possible, as they are significantly faster than kernel-mode constructs.

Coordination of threads occurs in hardware (that's why it's so fast).

But the Microsoft Windows operating system never detects that a thread is blocked on a primitive user-mode construct.

Because a thread pool blocking on a user-mode primitive construct is never considered blocked, the thread pool will not create a new thread to replace such a temporary thread.

These CPU instructions only block the thread for a relatively 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 will be scheduled again as quickly as possible.

Threads that want to obtain resources but cannot obtain them temporarily will continue to "spin" in user mode, which may waste a lot of CPU time. Threads are always running on one CPU, which we call "livelock".

Example:

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 that this data
    // member is accessed by multiple threads.
    private volatile bool _shouldStop;
}public class WorkerThreadExample
{    static void Main()
    {        // Create the worker thread object. This 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: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: terminating gracefully.
    // Main thread: worker thread has terminated.}

Kernel mode

Provided by the Windows operating system itself. They require calling functions implemented by the operating system kernel 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

Common lock ③: The Mutex class is a wrapper of the Win32 construct, which can cross application domains Boundaries are marshaled, can be used for multiple waits, and can be used to synchronize threads in different processes.

Advantages:

When a thread acquires resources owned by other threads through kernel-mode constructs, Windows blocks the thread to prevent it from wasting CPU time. When the resource becomes available, Windows resumes the thread, allowing it to access the resource. It does not occupy a CPU "spin".

Allows native and managed threads to be synchronized with each other.

Can synchronize threads running in different processes on the same machine.

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

The thread can block until all kernel-mode constructs it is cooperating with are available, or until any kernel-mode construct in the set is available.

Threads blocked on kernel mode constructs can specify a timeout value: if the desired resource cannot be accessed within the specified time, the thread can be unblocked and perform other tasks.

Disadvantages:

Switching a thread from user mode to kernel mode (or vice versa) incurs a huge performance penalty, which is why kernel constructs should be avoided. In addition, if the thread is blocked all the time, it will lead to "deadlock" (deadlock).

Deadlock is always due to livelock, because livelock wastes CPU time and wastes memory (thread stack, etc.), while deadlock only wastes memory.

Mixed construction

兼具上面兩者的長處。在沒有競爭的情況下,快而且不會阻塞(就像用戶模式)。在有競爭的情況,希望它被操作系統(tǒng)內(nèi)核阻塞。

技術(shù):ManualResetEventSlim類、SemaphoreSlim類、Monitor類、Lock類、ReaderWriterLockSlim類、CountdownEvent類、Barrier類、雙檢鎖.

常見鎖④:Monitor 通常更為可取,因為監(jiān)視器是專門為 .NET Framework 而設(shè)計的,因而它比Mutex可以更好地利用資源。盡管 mutex 比監(jiān)視器更為強大,但是相對于 Monitor 類,它所需要的互操作轉(zhuǎn)換更消耗計算資源。

常見鎖⑤:使用 lock (C#) 或 SyncLock (Visual Basic) 關(guān)鍵字是Monitor的封裝。通常比直接使用 Monitor 類更可取,一方面是因為 lock 或 SyncLock 更簡潔,另一方面是因為lock 或 SyncLock 確保了即使受保護(hù)的代碼引發(fā)異常,也可以釋放基礎(chǔ)監(jiān)視器。

常見鎖⑥:ReaderWriterLock 鎖,在某些情況下,可能希望只在寫入數(shù)據(jù)時鎖定資源,在不更新數(shù)據(jù)時允許多個客戶端同時讀取數(shù)據(jù)。ReaderWriterLock 類在線程修改資源時將強制其獨占訪問資源,但在讀取資源時則允許非獨占訪問。 ReaderWriter 鎖可用于代替排它鎖。使用排它鎖時,即使其他線程不需要更新數(shù)據(jù),也會讓這些線程等待。

雙檢鎖

常見鎖⑦:雙重檢查鎖定模式(也被稱為”雙重檢查加鎖優(yōu)化”,”鎖暗示”(Lock hint)) 是一種軟件設(shè)計模式用來減少并發(fā)系統(tǒng)中競爭和同步的開銷。

雙重檢查鎖定模式首先驗證鎖定條件(第一次檢查),只有通過鎖定條件驗證才真正的進(jìn)行加鎖邏輯并再次驗證條件(第二次檢查)。

它通常用于減少加鎖開銷,尤其是為多線程環(huán)境中的單例模式實現(xiàn)“惰性初始化”。惰性初始化的意思是直到第一次訪問時才初始化它的值。

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 (instance == null)
                {                    lock (syncRoot)
                    {                        if (instance == 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 string ToString()
        {            lock (syncRoot)
            {                int buf = --count;
                Thread.Sleep(20);                return buf + "_" + count.ToString();
            }
        }
    }static void Main(string[] args)
        {
            Task<string>[] tasks = new Task<string>[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);//設(shè)置超時5s
            watch.Stop();
            Console.WriteLine("Tasks running need " + watch.ElapsedMilliseconds + " ms." + "\n");            
for (int i = 0; i < tasks.Length; i++)
            {                //超時處理
                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 do work!");
                Thread.Sleep(200);
            }

            Console.ReadKey();
        }

輸出:

Tasks running need 298 ms.

Tick ID is 96_96

Tick ID is 99_99

Tick ID is 97_97

Tick ID is 98_98

Tick ID is 95_95

Tick ID is 94_94

Tick ID is 93_93

Tick ID is 92_92

Tick ID is 91_91

Tick ID is 90_90

Main thread do work!
Main thread do work!
Main thread do work!

以上就是從0自學(xué)C#12--線程同步解決方法匯總以及優(yōu)缺點的內(nèi)容,更多相關(guān)內(nèi)容請關(guān)注PHP中文網(wǎng)(www.miracleart.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

C# vs. C  : History, Evolution, and Future Prospects C# vs. C : History, Evolution, and Future Prospects Apr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

What is c# multithreading programming? C# multithreading programming uses c# multithreading programming What is c# multithreading programming? C# multithreading programming uses c# multithreading programming Apr 03, 2025 pm 02:45 PM

C# multi-threaded programming is a technology that allows programs to perform multiple tasks simultaneously. It can improve program efficiency by improving performance, improving responsiveness and implementing parallel processing. While the Thread class provides a way to create threads directly, advanced tools such as Task and async/await can provide safer asynchronous operations and a cleaner code structure. Common challenges in multithreaded programming include deadlocks, race conditions, and resource leakage, which require careful design of threading models and the use of appropriate synchronization mechanisms to avoid these problems.

C# .NET: Building Applications with the .NET Ecosystem C# .NET: Building Applications with the .NET Ecosystem Apr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

From Web to Desktop: The Versatility of C# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

.NET Framework vs. C#: Decoding the Terminology .NET Framework vs. C#: Decoding the Terminology Apr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

What are the benefits of multithreading in c#? What are the benefits of multithreading in c#? Apr 03, 2025 pm 02:51 PM

The advantage of multithreading is that it can improve performance and resource utilization, especially for processing large amounts of data or performing time-consuming operations. It allows multiple tasks to be performed simultaneously, improving efficiency. However, too many threads can lead to performance degradation, so you need to carefully select the number of threads based on the number of CPU cores and task characteristics. In addition, multi-threaded programming involves challenges such as deadlock and race conditions, which need to be solved using synchronization mechanisms, and requires solid knowledge of concurrent programming, weighing the pros and cons and using them with caution.

C# .NET: Exploring Core Concepts and Programming Fundamentals C# .NET: Exploring Core Concepts and Programming Fundamentals Apr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

See all articles