C # Multithreading

Source: Internet
Author: User

Multithreading has been used in recent projects. I would like to take this opportunity to learn and summarize it.

1. lock and Monitor

Lock is the most commonly used. The reason is that it is easy to use and the code is clean. It is implemented through Monitor internally. It acquires the exclusive lock through Monitor. Enter (obj) and releases the lock through Monitor. Exit (obj. The code in it becomes a critical section. When one thread enters, the other thread can only wait for the exclusive lock.

The lock parameter must be an object based on the reference type. Do not use basic types such as bool or int. In this way, synchronization is not allowed because the lock parameter must be an object. If the basic type is input, the boxing operation is bound to occur, so that each lock will be a new and different object. It is best to avoid using public or program-controlled object instances, because this may lead to deadlocks. In particular, do not use a string as the lock parameter, because the string is "Temporarily" by CLR, that is, the given string in the entire application only has one instance, so it is more likely to cause a deadlock. We recommend that you use private or protected members that are not "Temporarily" as parameters. In fact, some classes already provide members dedicated for lock. For example, the Array type provides SyncRoot, and many other collection types also provide SyncRoot.

Therefore, pay attention to the following points when using lock:

A. If the instance of a class is public, it is best not to lock (this ). Because the person using your class may not know that you have used lock. If he has a new instance and locks the instance, it is easy to cause a deadlock.

B. If MyType is public, do not lock (typeof (MyType ))

C. Never lock a string

Monitor provides more control functions for us:

A. The TryEnter method can determine whether the current critical section can enter without waiting. However, if this function returns True, it indicates that it has entered the street-facing area and does not need to call the Enter method. In addition, you can also pass in the Try timeout time for more flexible control.

B. The Wait method allows the thread to release all current resources and lock it. Other threads can enter the street area, and the thread is suspended when Wait is called. It continues until other threads call Pulse to wake up the thread.

C. Pluse (Pluse, PluseAll) method wake up the waiting thread to continue working. Together with the Wait method, the Wait and wake-up mechanisms can be implemented.

2. Mutex and Semaphore

Both of the two can be synchronized across processes through naming parameters. The difference is that Mutex allows only one thread at a time, and Semaphore allows N threads to enter. When N = 1, it is consistent with Mutex.

3. AutoResetEvent and ManualResetEvent

The only difference between them is whether the status automatically changes from terminated to non-terminated after the thread is activated. AutoResetEvent automatically becomes non-terminated, that is, one AutoResetEvent can only activate one thread. ManualResetEvent is not terminated until its Reset method is called. Before that, ManualResetEvent can activate any number of threads.

4. SynchronizationAttribute and MethodImplAttribute

When we determine that a class instance can only be accessed by one thread at a time, we can directly mark the class as Synchronization. In this way, CLR will automatically implement a Synchronization mechanism for this class.

We can ensure that the instance of the class cannot be accessed by multiple threads at the same time.
A. in the class declaration, add the System. Runtime. Remoting. Contexts. SynchronizationAttribute attribute.
B. inherit to System. ContextBoundObject
Note that the class must inherit from System. ContextBoundObject. In other words, the class must be context-bound.

If the critical section spans the entire method, that is, the code inside the method needs to be locked, it is easier to use the MethodImplAttribute attribute. The entire locking method is not flexible and is not recommended.

5. ReaderwriterLock

When you use ReaderWriterLock for resource access, if the resource does not obtain the write exclusive permission at a certain time point, you can obtain multiple read access permissions and the exclusive permission for a single write, if the write exclusive permission has been obtained at a certain time point, other read access permissions must wait.

6. Interlocked

Baidu's interview question:

Which of the following statements does not need to be synchronized when multiple threads operate on int variable x:
A. x = y; B. x ++; C. ++ x; D. x = 1;

The answer is D, which can be ++, -- and assign values. That is to say, it cannot be completed by one machine command. The value assignment operation requires that the original operand be put into the register and then transferred to the destination operand. While ++, -- addition and subtraction must be performed after the registers are placed. Thread switching may occur during these operations. Interlocked provides atomic operations for addition, subtraction, and assignment.

7. volatile keywords

The meaning of volatile is to tell the processor not to put me into the working memory. Please operate on me directly in the main memory. Therefore, when multiple threads access the variable at the same time, the main memory is operated directly, essentially sharing the variables. But volatile cannot implement real synchronization, because its operation level only stays at the variable level rather than the atomic level. If it is in a single-processor system, there is no problem. The variable in the main memory has no chance to be modified by others, because there is only one processor, which is called processor Self-Consistency. However, in a multi-processor system, problems may occur. Each processor has its own data cach, and the updated data may not be written back to the primary storage immediately. Therefore, non-synchronization may occur, but this situation is very difficult, because the read and write speed of cach is quite fast and the flush frequency is quite high. It can only happen during stress testing, and the probability is very small.


Reference: http://www.cnblogs.com/michaelxu/archive/2008/09/20/1293716.html

Http://blog.csdn.net/morewindows/article/details/7392749

Http://archlord.blog.hexun.com/27358184_d.html













This article from the "only text cut through time and space" blog, please be sure to keep this source http://arthurshayne.blog.51cto.com/3491820/1216493

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.