Typical scenarios and problems of Thread Synchronization in. net

Source: Internet
Author: User

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 running in the same application 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.

Multiple Threads compete for exclusive Resources
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 ). Typical code:Copy codeThe Code is as follows: var objLock = new Object ();
Var thread1 = new Thread () =>
{
Lock (objLock)
{
AccessResource ();
}
});
Var thread2 = new Thread () =>
{
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.Copy codeThe Code is as follows: var mutex = new Mutex (false, "name ");
Var thread1 = new Thread () =>
{
Try
{
Mutex. WaitOne ();
AccessResource ();
}
Finally
{
Mutex. ReleaseMutex ();
}
});
Var thread2 = new Thread () =>
{
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 which a producer thread is generating data to be processed and a consumer thread is processing data. Generally, 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.Copy codeThe Code is as follows: 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 above example, the producer generates a data to be processed at an interval of 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.