Thread data sorting and thread sorting

Source: Internet
Author: User

Thread data sorting and thread sorting

If multiple threads are running simultaneously in the process where your code is located, these threads may run the code at the same time. If the result of each running is the same as that of a single thread, and the value of other variables is the same as expected, it is thread-safe.
In other words, the interface provided by a class or program is an atomic operation for a thread or the switching between multiple threads does not lead to ambiguity in the execution result of this interface, that is to say, we do not need to consider synchronization issues.
Thread security issues are caused by global variables and static variables.
If each thread only performs read operations on global variables and static variables without write operations, this global variable is thread-safe; if multiple threads perform read/write operations on a variable at the same time, thread synchronization is generally considered; otherwise, thread security may be affected.

The purpose of lock is to prevent concurrent operations during multi-thread execution. With the reference type of lock, only one thread can be operated at a time point in the locked area.

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

 

Class Program {static void Main (string [] args) {threda t = new threda (); threda. obj. I = 10; Thread th1 = new Thread (new ThreadStart (t. hhh); th1.Name = "th1"; th1.Start (); Thread th1 = new Thread (new ThreadStart (t. hhh); th2.Name = "Th1"; th2.Start () ;}} class threda {public static sss obj = new sss (); public void hhh () {lock (obj) {for (int I = 0; I <7; I ++) {Thread. sleep (500); if (obj. i> 0) {obj. I --; Console. writeLine ("current Thread name:" + Thread. currentThread. name + ", obj. I = "+ obj. i) ;}}} class sss {public int I ;}

 

 

There are differences between the locking and non-locking operations:

After the lock: The I value will decrease one by one, and there will be no jumps, no repeated output, until the 0 value;

No lock: The I value output will jump, not consecutive decrease, and the-1 value output may also appear;

Cause: After the lock is applied, only one thread can execute the code in the locked area at a time point. Both threads execute the code sequentially, so there will be no interrupted output.

 

 

 

C # understand lock

I. Why do I need to lock? What does it lock?

When we use threads, the most efficient method is asynchronous, that is, each thread runs simultaneously without mutual dependency and waiting. However, when different threads need to access a resource, the synchronization mechanism is required. That is to say, when reading and writing the same resource, we need to make the resource be operated by only one thread at a time to ensure that each operation is effective immediately, that is, to ensure the atomicity of its operations. Lock is the most common synchronization method in C #, in the format of lock (objectA) {codeB }.


Lock (objectA) {codeB} seems simple and actually has three meanings, which is important for proper use of it:
1. Is objectA locked? Otherwise, wait until the objectA is released.
2. When codeB is executed after the lock, other threads cannot call codeB or use objectA.
3. After codeB is executed, release objectA and codeB can be accessed by other threads.


Ii. What happened to lock (this?


Let's look at an example:

Using System; using System. threading; namespace Namespace1 {class C1 {private bool deadlocked = true; // lock is used in this method, we hope that the lock code can only be accessed by one thread at a time by public void LockMe (object o) {lock (this) {while (deadlocked) {deadlocked = (bool) o; Console. writeLine ("Foo: I am locked :("); Thread. sleep (500) ;}}// the public void DoNotLockMe () {Console. writeLine ("I am not locked :)") ;}} class Program {static void Main (string [] args) {C1 c1 = new C1 (); // call LockMe in Thread t1 and set deadlock to true (deadlock will occur) Thread t1 = new Thread (c1.LockMe); t1.Start (true); Thread. sleep (100); // lock c1 lock (c1) in the main thread {// call the method c1.DoNotLockMe () that is not locked; // call the method that is locked, and try to remove deadlock c1.LockMe (false );}}}

 

Copy code

In thread t1, LockMe calls lock (this), that is, c1 in the Main function. At this time, when lock (c1) is called in the Main thread, you must wait until the lock block in t1 is executed to access c1, that is, all c1-related operations cannot be completed, so we can see that c1.DoNotLockMe () is not executed.


Slightly modify the C1 code:

 

Class C1 {private bool deadlocked = true; private object locker = new object (); // This method uses lock, we hope that the lock code can only be accessed by one thread at a time by public void LockMe (object o) {lock (locker) {while (deadlocked) {deadlocked = (bool) o; Console. writeLine ("Foo: I am locked :("); Thread. sleep (500) ;}}// the public void DoNotLockMe () {Console. writeLine ("I am not locked :)");}}

 

Copy code

This time, we use a private member as the lock variable. In LockMe, we only lock this private locker, not the entire object. When the program is re-run, we can see that although t1 has a deadlock, DoNotLockMe () can still be accessed by the main thread; LockMe () still cannot be accessed, the reason is that the locked locker has not been released by t1.


Key points:
1. the disadvantage of lock (this) is that when a thread (for example, t1 in this example) executes a method of this class using "lock (this)" (for example, LockMe () in this example ()) after an object is locked, the entire object cannot be accessed by other threads (such as the main thread in this example)-because many people in other threads (such as the main thread in this example) when this class is used, code similar to lock (c1) is used.
2. Locking is not only about the code in the lock segment, but also about thread security.
3. We should use private objects that do not affect other operations as locker.
4. when using lock, the locked object (locker) must be of the reference type. If it is of the value type, this will cause the object to be packed into a new reference object each time the lock is performed (in fact, if the value type is used, the C # Compiler (3.5.30729.1) will give an error during compilation ).

-- This document is from the network.

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.