Threading Data Grooming

Source: Internet
Author: User

If your code is in a process where multiple threads are running at the same time, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe.
Or, the interface provided by a class or program for a thread is an atomic operation or a switchover between multiple threads does not result in ambiguity in the execution of the interface, that is, we do not have to consider the problem of synchronization.
Thread safety issues are caused by global variables and static variables.
In general, this global variable is thread-safe if there are only read operations on global variables and static variables in each thread, and if multiple threads perform read and write operations on a variable at the same time, it is generally necessary to consider thread synchronization, otherwise it may affect thread safety.

The purpose of lock is to prevent concurrent operation problems when multithreaded execution, plus an object of the reference type of lock, which allows only one thread to operate at a time within its locked area.

Lock can only lock a reference type variable, that is, lock an address

classProgram {Static voidMain (string[] args) {Threda T=NewThreda (); THREDA.OBJ.I=Ten; Thread Th1=NewThread (NewThreadStart (t.hhh)); Th1. Name="Th1"; Th1.        Start (); Thread Th2=NewThread (NewThreadStart (t.hhh)); Th2. Name="Th2"; Th2.        Start (); }    } classThreda { Public StaticSSS obj =NewSSS ();  Public voidHHH () {Lock(obj) { for(inti =0; I <7; i++) {Thread.Sleep ( -); if(Obj.i >0) {obj.i--; Console.WriteLine ("Current thread Name:"+thread.currentthread.name+", obj.i="+obj.i); }                }            }        }            }    classSSS { Public inti; }

The results of locking and non-lock operation are different:

After locking: The value of I will be reduced by a few, will not jump, will not appear repeated output, until 0 value;

No lock: I value output will appear jump, discontinuous decrement, may also appear-1 value output;

Cause: After locking, only one thread at a time can execute the code of the locked area, and two threads are executed sequentially, so there is no intermittent output.

C # Understanding Lock

I. Why do you have to Lock,lock?

When we use threads, the most efficient way is, of course, asynchronous, where each thread runs at the same time and does not depend on and waits on each other. However, when different threads need to access a resource, it is necessary to synchronize the mechanism, that is, when reading and writing the same resource, we have to make the resource can only be manipulated by one thread at a time to ensure that each operation is effective and instantaneous, that is, the atomicity of its operation. Lock is the most commonly used synchronization method in C #, in the form of lock (OBJECTA) {codeb}.


Lock (OBJECTA) {Codeb} looks simple and actually has three meanings, which is essential for proper use:
1. Has objecta been lock? No, I'll lock it, or I'll wait until Objecta is released.
2. After lock is executed codeb other threads cannot call Codeb and cannot use Objecta.
3. Objecta is released after execution of Codeb, and codeb can be accessed by other threads.


Two. What happened to lock (this)?


Let's look at an example:

usingSystem;usingSystem.Threading;namespacenamespace1{classC1 {Private BOOLdeadlocked =true; //This method uses lock, and we want lock's code to be accessible only by one thread at a time         Public voidLockme (Objecto) {Lock( This)            {                 while(deadlocked) {deadlocked= (BOOL) O; Console.WriteLine ("foo:i am Locked:("); Thread.Sleep ( -); }            }        }        //methods that all threads can access concurrently         Public voidDonotlockme () {Console.WriteLine ("I am not locked:)"); }    }    classProgram {Static voidMain (string[] args) {C1 C1=NewC1 (); //call Lockme in the T1 thread and set deadlock to True (deadlock will occur)Thread T1 =NewThread (C1.            Lockme); T1. Start (true); Thread.Sleep ( -); //in the main thread, lock C1            Lock(C1) {//call a method that is not lockC1.                Donotlockme (); //call the Lock method and attempt to dismiss the deadlockC1. Lockme (false); }        }    }

Copy Code

In the T1 thread, Lockme calls lock (this), which is the C1 in the main function, when you call Lock (C1) in the main thread, you must wait for the lock block in T1 to complete before you can access C1, that is, all C1-related operations cannot be completed. So we see even C1. None of the Donotlockme () has been executed.


Make a slight change to the C1 code:

classC1 {Private BOOLdeadlocked =true; Private ObjectLocker =New Object(); //This method uses lock, and we want lock's code to be accessible only by one thread at a time         Public voidLockme (Objecto) {Lock(locker) { while(deadlocked) {deadlocked= (BOOL) O; Console.WriteLine ("foo:i am Locked:("); Thread.Sleep ( -); }            }        }        //methods that all threads can access concurrently         Public voidDonotlockme () {Console.WriteLine ("I am not locked:)"); }    }

Copy Code

This time we use a private member as the lock variable (locker), and in Lockme we only lock the private locker, not the entire object. At this time rerun the program, you can see that although T1 deadlock, Donotlockme () can still be accessed by the main thread, Lockme () is still inaccessible, because the locked locker has not been released by T1.


Key points:
1. The disadvantage of lock (this) is that after a thread (for example, T1) locks an object by executing a method of that class using "lock" (for example, Lockme () of this example), the entire object cannot be accessed by another thread (for example, the main thread of this example)- This is because many people use lock (c1)-like code when using the class in other threads, such as the main thread of this example.
2. Locking is not just the code in the lock segment, the lock itself is thread-safe.
3. We should use private objects that do not affect other operations as locker.
4. When using lock, the lock object (locker) must be a reference type, if it is a value type, will cause the object to be boxed into a new reference object each time lock is used (in fact, if you use a value type, the C # compiler (3.5.30729.1) An error will be given at compile time).

-This data is from the network.

Threading Data Grooming

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.