Typical scenarios and problems of Thread Synchronization in. Net (1)

Source: Internet
Author: User
ArticleDirectory
    • Directory
    • Multiple Threads compete for exclusive Resources

When multithreading is used for programming, there are some typical thread synchronization problems. For these problems,. NET provides a variety of classes to solve. In addition to the scenario itself, an important question is whether these threads are in the same application.ProgramRun in the domain. If the threads are running in the same application domain, you can use some so-called "lightweight" synchronization classes. Otherwise, you need to use other classes, these classes are packaging the synchronization primitives provided by the operating system, which consume more resources. Here I will introduce some typical application scenarios and related issues.

Dedicated resources for multi-thread directory Competition

Some resource threads are usually exclusive. If multiple threads need to access the required resources at the same time, a contention problem occurs. Such resources include files, printers, serial ports, and all non-thread-safe class objects (most classes in class libraries ). TypicalCode:

 
VaR objlock =NewObject (); var thread1 =NewThread () => {Lock(Objlock) {accessresource () ;}}); var thread2 =NewThread () => {Lock(Objlock) {accessresource ();}});

In the above Code, the lock keyword is actually a syntactic sugar of the monitor class. Any object (non-value type) has a lock area, monitor. the enter method attempts to lock the region. If the lock is successful, the thread will own the object and the thread will be suspended. Note the following for objlock objects:

    • Do not lock this
    • Do not lock type
    • Do not lock strings
    • Do not lock value-type objects

For the same class, there are usually many different instances. In this case, the lock may be locked to multiple different objects, thus making the lock invalid. There are two reasons not to lock the type. One is that the generation of type-class objects is relatively slow, and the other is that the type is usually public, this may be locked in different places of the program. This is actually a engineering problem, mainly to prevent the introduction of bugs. Do not lock the string class, which is a factor. All strings with the same nominal value actually share the same object, so they may be accidentally locked by other code like type, such a bug is hard to be ruled out. Do not lock the value type, because the value type itself cannot be locked. to lock it, the compiler value will pack it, and a different object instance will be generated each time it is packed, in this way, the lock will have no effect.

The above code is valid because all threads are in the same application, that is, resource contention between processes is not involved. For resource contention among multiple processes, you can use the mutex class. Mutex has two different usage methods: anonymous mutex and named mutex. The named mutex is shared throughout the operating system, so it can be used for inter-process synchronization.

 

VaR mutex =NewMutex (False,"Name"); Var thread1 =NewThread () => {Try{Mutex. waitone (); accessresource ();}Finally{Mutex. releasemutex () ;}}); var thread2 =NewThread () => {Try{Mutex. waitone (); accessresource ();}Finally{Mutex. releasemutex ();}});
 
Note that the mutex must be released at the end of the thread.
One-to-one producer/consumer model

In this model, a producer thread is generating data to be processed, and a consumer thread is processing data. Generally, the data is stored in a cache. In some cases, each time the producer generates a data, it is put into the cache, and set the semaphore (waithandle) to notify the consumer thread to process it. The consumer continuously processes data. If it finds that all the data has been processed, it is blocked to wait for the producer thread to generate data. There are two types of semaphores: autoresetevent and manualresetevent. The former feature is that each time a signal is set, a blocked thread will be awakened, and the semaphore is not set immediately. The latter State is completely controlled by the program. It may wake up multiple threads at a time, or it may not wake up another thread. Sample Code for this model.

 Using System; Using System. Collections. Generic; Using System. Threading; Namespace Threadcancle { Public   Class Producerconsumer2 { Public   Static   Void Main () {var autoresetevent =New Autoresetevent ( False ); Var queue = New Queue < Int > (); Var producterthread = New Thread () => {var Rand = New Random (); While ( True ) {VaR Value = Rand. Next (100 ); Lock (Queue) {queue. enqueue ( Value );} Thread. Sleep (RAND. Next (400,120 0); console. writeline ( "Generated data {0 }. " , Value ); Autoresetevent. Set () ;}}); var consumerthread = New Thread () => { While ( True ) {Autoresetevent. waitone (); Int   Value = 0; Bool Hasvalue = True ; While (Hasvalue ){ Lock (Queue) {hasvalue = (queue. Count> 0 ); If (Hasvalue ){ Value = Queue. dequeue () ;}} thread. Sleep (800); console. writeline ( "Processed data {0 }. " , Value ) ;}}); Producterthread. Start (); consumerthread. Start (); console. Readline ();}}}

in the preceding example, the producer generates a data to be processed every 0.4-1.2 seconds, and the consumer's processing capability is to process one data every 0.8 seconds. The producer continuously generates data, puts it into the queue, and then wakes up the consumer thread. The consumer thread blocks all data in the queue. It should be noted that the consumer thread and producer thread will simultaneously access the queue object, and each time they are accessed, they must be locked. The minimum time used must be followed when the lock is executed. Once used, the lock should be released immediately.

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.