C # thread (2)

Source: Internet
Author: User

Continue with the previous C # thread discussion (1). Here we will introduce the common concepts and precautions for thread synchronization.
3. Synchronization
An important aspect of using a thread is to synchronously access any variable accessed by multiple threads.
(1) "synchronization": synchronization means that only one thread can access the variable at a certain time.
Synchronization only occurs in the following scenarios:At least one thread needs to write one variable. At the same time, other threads are reading or writing the same variable.. This is in sync with the threads in the university course "Operating System.
C # provides a very simple method for Synchronous access variables, that is, using the keyword lock. Code is cheap. For example, this method has been used to "ensure that only one instance of a class: Singleton mode:

Code
Using System;
Using System. Threading;
///   <Summary>
/// Singleton
///   </Summary>
Public   Class Windowstaskmanager
{
Private   Static Windowstaskmanager WTM;
Private   Static   Readonly   Object Syncroot =   New   Object (); //  ProgramCreate a static read-only process auxiliary object during running.
Private Windowstaskmanager ()
{
}
Public   Static Windowstaskmanager createsinglewtm ()
{
Lock (Syncroot) // Lock synchronous access variable
{
If (WTM =   Null )
{
WTM =   New Windowstaskmanager ();
}
}
Return WTM;
}
}

The lock statement puts variables in brackets to wrap objects. It is called an exclusive lock or exclusive lock. When a compound statement with the lock keyword is executed, the exclusive lock is retained. When a variable is encapsulated in an exclusive lock, other threads cannot access the variable. IfCodeWhen an exclusive lock is used to execute a composite statement, the thread will lose its "time slice ". If the thread that obtains the time slice tries to access the variable syncroot, it will be rejected. Windows puts other threads in sleep state until the exclusive lock is lifted.
PS: In the above Code, we lock an object. For the special type of String object, we must use it with caution. For example, the following code:

Code
Class Locktestone
{
Private   String Strsync =   "" ;
Public   Void Dosomething ()
{
Lock (Strsync)
{
// Do something
}
}
}

Class Locktesttwo
{
Private   String Strsync2 =   "" ;
Public   Void Dosomething2 ()
{
Lock (Strsync2)
{
// Do something
}
}
}

Originally, the methods in the locktestone and locktestone2 classes have no relationship at all, but here, when the dosomething2 method is executed, if the other thread is executing the dosomething method, it has to wait! The two variables (strsync and strsync2) are both assigned as "" (empty string) during compilation, and. NET will point these two variables to the sameDetention pool(Strsync and strsync2 are in the detention pool .). Therefore, two locks seem to lock two irrelevant objects, but they are actually locking the same object. So, to be precise, we should not lock the strings in the detention pool.
(2) synchronization problems: Dead Lock and Race Condition)
Thread Synchronization is very important, but it should be used with caution because it will reduce performance. There are two reasons: First, placing the unlock lock on the object will cause some system overhead. The second reason is more important,The more threads are used, the more threads waiting to release objects. If a thread places a lock on the object, other threads that need to access the object can only pause the execution until the lock is unlocked. Therefore, the less code written in the lock block, the better, to avoid thread synchronization errors. In a sense, the lock statement temporarily disables the multi-thread function of the application and deletes the advantages of multithreading.
The use of thread synchronization has potential risks, mainly manifested in deadlock and race conditions.
A. deadlock: a deadlock is an error and must be accessed by both threads.Mutual lock ResourcesOccurs. For example, the following code:

Code
/* Run the following code in thread 1: */
// A and B are object references that can be accessed by both threads.
Lock ()
{
// Do something
Lock (B)
{
// Do something
}
}

/* Thread 2 run the following code */
Lock (B)
{
// Do something
Lock ()
{
// Do something
}
}

In the code above, depending on the time when thread 1 and thread 2 encounter different statements, the following may occur: thread 1 is locked on a, and thread 2 is locked on B. Soon, thread 1 began to encounter the lock (B) statement and immediately entered the sleep state, waiting for the lock on B to be released. Then, the second thread encounters the lock (a) statement and immediately enters the sleep state, waiting for the lock on a to be released.HoweverThe lock on a will never be unlocked, because thread 1 has this lock, which is currently in sleep state and won't "wake up" until the lock on B is unlocked. Before thread 2 is woken up, the lock on thread B will not be unlocked, so that thread 1 and thread 2 will wait for each other to release resources (and eventually consume resources ), in this way, a deadlock occurs.
Solution to the deadlock: Let the two threads declare the lock on the object in the same order. The correct code is as follows:

Code
/* Run the following code in thread 1: */
// A and B are object references that can be accessed by both threads.
Lock ()
{
// Do something
Lock (B)
{
// Do something
}
}

/* Thread 2 runs the following code (the lock order for a and B is the same as thread 1) */
Lock ()
{
// Do something
Lock (B)
{
// Do something
}
}

B. competitive conditions
Race conditions are more subtle than deadlocks. It rarely interrupts process execution, but may cause data corruption. When several thread views access the same data, but the execution of other threads is not considered, a race condition occurs.
Note: The competition conditions are not clear in one or two sentences. You can refer to the relevant materials and the university textbook "operating system" for details. I will not go into details here.

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.