Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example Analysis of thread lock of C # multithread

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of thread lock case analysis of C# multithreading, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this thread lock example analysis article of C# multithreading. Let's take a look.

1. Mutex class

"mutex" is an abbreviated form of the term "mutually exclusive", that is, mutually exclusive quantities. Mutexes are similar to the Monitor mentioned in the critical section. Only threads with mutexes have access to resources. Since there is only one mutex, it determines that this shared resource will not be accessed by multiple threads at the same time. The thread that currently occupies the resource should hand over the mutex after the task is processed so that other threads can access the resource after obtaining it. Mutexes are more complex than critical areas, because using mutexes not only enables secure sharing of resources in different threads of the same application, but also securely shares resources between threads of different applications. The mutex in .net is represented by the Mutex class.

II. The use of Mutex

Mutex is not suitable for synchronization with mutual message notification; on the other hand, local Mutex should be replaced by Monitor/lock; while cross-application synchronization with mutual message notification is more appropriate for EventWaiteHandle/AutoResetEvent/ManualResetEvent. As a result, there don't seem to be many scenarios where Mutex is used in. Net. However, Mutex has the most common use: to control that only one instance of an application can run. The system relies on this name attribute to identify a unique Mutex.

Private static Mutex mutex = null; / / is set as a Static member to hold Mutexstatic void Main () {bool firstInstance; mutex = new Mutex (true, @ "Global\ MutexSampleApp", out firstInstance) throughout the program life cycle; try {if (firstInstance) {Console.WriteLine ("We are the first instance!") ;} else {Console.WriteLine ("warning, an instance is already running!") ; return;}} finally {/ / only the first instance gets control, so ReleaseMutex is needed only in this case, otherwise an exception will be thrown. If (firstInstance) {mutex.ReleaseMutex ();} mutex.Close (); mutex = null;}} III. Semaphore semaphore 1, introduction

Semaphore is a semaphore used in the operating system to control thread synchronization mutexes. When writing multithreaded programs, Semaphore semaphores can be used to coordinate multithread parallelism, so that each thread can share resources reasonably and ensure that the program runs correctly.

2. Initialize

Initializing Semaphore can be treated as opening a thread pool, with initialCount representing the remaining space and maximumCount representing the maximum capacity. The example is as follows. The current vacancy is 0 and the maximum capacity is 1:

Semaphore sem = new Semaphore (0,1); 3, WaitOne () and Release ()

The two common methods of Semaphore are WaitOne () and Release ().

Using the WaitOne () method is equivalent to waiting for a thread to exit, while using the Release () method allows a thread to exit.

Assuming that initialCount and maximumCount are both 5, the thread pool starts with 5 empty positions, and there are only 5 positions in total. When the number of parallel threads exceeds 5, first use the WaitOne () method to wait, and find that there is a vacancy in turn, minus 1 for each vacancy, until the initialCount is 0 after entering 5 threads, then the subsequent thread waits until a thread calls the Release () method. Actively exit the thread pool, the vacancy is added by 1, and the waiting thread can continue to enter the thread pool.

The following code example creates a semaphore with a maximum count of 3 and an initial count of zero. The example starts five threads, which prevents waiting for semaphores. The main thread uses the Release (Int32) method overload to increase the semaphore count to its maximum value, allowing three threads to enter the semaphore. Each thread waits for a second to simulate work using the Thread.Sleep method, and then Release () calls method overloading to release the semaphore. Each time the semaphore is released, the previous semaphore count is displayed. Console message tracking semaphore is used. The simulation interval for each thread increases slightly, making the output easier to read.

Private static Semaphore _ pool;private static int _ padding;public static void Main () {_ pool = new Semaphore (0,3); for (int I = 1; I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report