"C #" threading issues

Source: Internet
Author: User

multithreaded programming is not easy for many programmers, and intermittently encounters problems that are difficult to discover when starting multiple threads that access the same data. You will also encounter these problems if you use tasks, parallel LINQ, or parallel classes. To avoid this series of problems, the development program must be aware of synchronization issues and other issues that may occur with multiple threads. Let's take a look at race conditions and deadlocks.

I. Conditions of contention

A race condition occurs if two or more threads access the same object, or access a shared state that is not synchronized (for example, an entity for EF). to illustrate the race condition, we define a StateObject class that contains an int field and a changestate () method. In the implementation code of the method, verify that the state variable contains 5. If it is included, the value is incremented. Then use the Trace.Assert method to verify that the state contains 6. after you increment 1 for a variable that contains 5, you may want the value of the variable to be 6. But that is not necessarily the case. For example, if a thread has just finished executing an if (state==5) code, it is called by another thread, and the scheduler runs another thread. The second thread has just entered the IF statement because the value of state is still 5, so it is incremented to 6. Now that thread 1 is dispatched again, the result state becomes 7, and the race condition occurs.

 Public classstateobject{Private intState=5;  Public voidChangestate (intLoop) {        if(state==5) { state++; Trace.Assert ( State==6,"contention occurs"+loop+"Loops"); } State=5; }}

This is done by defining a method for the task to verify that the Racecondition () method of the Sametask class takes a StateObject class as a parameter. In an infinite while loop, its method is called. The variable i is used only to indicate the number of loops.

 Public classsampletask{ Public voidRacecondition (Objecto) {Trace.Assert (o isStateObject,"o must be a stateobject type"); StateObject State=o asStateObject; intI=0;  while(true) {state. Changestate (i++); }    }}

Here we create a new StateObject object in the Main method, which is shared by all tasks. Let's take a look at the code

Static void Main () {    var state=New  stateobject ();      for (int i=0;i<; i++) {        Task.Factory.StartNew (new  Sampletask (). racecondition,state);    }    Thread.Sleep (10000);}

  

Run the program, we will see the error prompt, start the program multiple times, will get different results, then how we avoid similar problems, we can lock the shared object, which can be completed in the thread: The following lock statement to lock the shared state variable in the thread. Only one thread can handle a shared object in a locked block. Because this object is shared among all threads, if one thread locks the object, the other threads must wait for the lock to be unlocked. Once the lock is accepted, the thread has the lock until you change the lock block, and the lock is unlocked at the end.

 Public classsampletask{ Public voidRacecondition (Objecto) {Trace.Assert (o isStateObject,"o must be a stateobject type"); StateObject State=o asStateObject; intI=0;  while(true) {state. Changestate (i++); Lock(state) {state. Changestate (i++); }        }    }}

when you use a shared object, you can also set the shared object as a thread-safe object, in addition to locking. where the Changestate () method contains the lock statement, because the state variable itself cannot be locked (only the reference type can be used for locking), a variable of type object is defined and used for the lock statement.

 Public classstateobject{Private intState=5; Private Objecto=New Object();  Public voidChangestate (intLoop) {        Lock(o) {if(state==5) { state++; Trace.Assert ( State==6,"contention occurs"+loop+"Loops"); } State=5; }    }}

Two, deadlock
Too many locks can be problematic, with at least two threads suspended in a deadlock and waiting for the object to unlock. Since two threads are waiting for each other, there is a deadlock, and the subsequent thread waits indefinitely.
Let's look at a deadlock example, we create two tasks,

varstate1=Newstateobject ();varState2=NewStateObject (); Task.Factory.StartNew (NewSampletask (STATE1,STATE2). DEADLOCK1); Task.Factory.StartNew (NewSampletask (STATE1,STATE2). DEADLOCK1); Public classsamplethread{Privatestateobject S1; Privatestateobject S2;  Publicsamplethread (stateobject s1,stateobject s2) { This. s1=S1;  This. s2=S2; }         Public voidDeadlock1 () {intI=0;  while(true){            Lock(S1) {Lock(S2) {S1.                    Changestate (i); S2. Changestate (i++); Console.WriteLine ("{0}", i); }            }        }    }         Public voidDeadlock2 () {intI=0;  while(true){            Lock(S2) {Lock(S1) {S1.                    Changestate (i); S2. Changestate (i++); Console.WriteLine ("{0}", i); }            }        }    }}

The Deadlock1 () and DeadLock2 () methods now change the state of two objects S1, S2, which is prone to deadlock, the previous method locks S1 First, then locks S2, while 21 is the opposite, now it is possible that the former S1 lock is lifted, a thread switch occurs, The Deadlock2 method starts running and locks the S2, then the second thread now waits for the S1 lock to unlock, because it waits, so the thread scheduler dispatches the first thread again, but the first thread waits for the S2 to be unlocked, causing two threads to wait, so long as the lock block is not finished, it will not unlock , the result is a deadlock.

"C #" threading issues

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.