15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Threading issues ❘ 513<br />

}<br />

}<br />

}<br />

state++;<br />

Trace.Assert(state == 6, "Race condition occurred after " +<br />

loop + " loops");<br />

}<br />

state = 5;<br />

code snippet ThreadingIssues/SampleTask.cs<br />

deadlock<br />

Too much locking can get you in trouble as well. In a deadlock, at least two threads halt <strong>and</strong> wait for<br />

each other to release a lock. As both threads wait for each other, a deadlock occurs <strong>and</strong> the threads<br />

wait endlessly.<br />

To demonstrate deadlocks, two objects of type StateObject are instantiated <strong>and</strong> passed with the<br />

constructor of the SampleTask class. Two tasks are created: one task running the method Deadlock1() <strong>and</strong><br />

the other task running the method Deadlock2():<br />

var state1 = new StateObject();<br />

var state2 = new StateObject();<br />

new Task(new SampleTask(state1, state2).Deadlock1).Start();<br />

new Task(new SampleTask(state1, state2).Deadlock2).Start();<br />

code snippet ThreadingIssues/Program.cs<br />

The methods Deadlock1() <strong>and</strong> Deadlock2() now change the state of two objects: s1 <strong>and</strong> s2. That’s why<br />

two locks are generated. The method Deadlock1() first does a lock for s1 <strong>and</strong> next for s2. The method<br />

Deadlock2() first does a lock for s2 <strong>and</strong> then for s1. Now, it may happen from time to time that the lock<br />

for s1 in Deadlock1() is resolved. Next, a thread switch occurs, <strong>and</strong> Deadlock2() starts to run <strong>and</strong><br />

gets the lock for s2. The second thread now waits for the lock of s1. Because it needs to wait, the thread<br />

scheduler schedules the first thread again, which now waits for s2. Both threads now wait <strong>and</strong> don’t release<br />

the lock as long as the lock block is not ended. This is a typical deadlock.<br />

public class SampleThread<br />

{<br />

public SampleThread(StateObject s1, StateObject s2)<br />

{<br />

this.s1 = s1;<br />

this.s2 = s2;<br />

}<br />

private StateObject s1;<br />

private StateObject s2;<br />

public void Deadlock1()<br />

{<br />

int i = 0;<br />

while (true)<br />

{<br />

lock (s1)<br />

{<br />

lock (s2)<br />

{<br />

s1.ChangeState(i);<br />

s2.ChangeState(i++);<br />

Console.WriteLine("still running, {0}", i);<br />

}<br />

}<br />

}<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!