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.

530 ❘ ChaPTer 20 threAds, tAsks, And synchrOnizAtiOn<br />

}<br />

}<br />

Console.WriteLine("Calculation completed from task {0}. {1} " +<br />

"times a, {2} times z", Task.Current.Id, charCount[0],<br />

charCount[25]);<br />

barrier.RemoveParticipant();<br />

Console.WriteLine("Task {0} removed from barrier, " +<br />

"remaining participants {1}", Task.Current.Id,<br />

barrier.ParticipantsRemaining);<br />

return charCount;<br />

With the Main() method, a Barrier instance is created. In the constructor, you can specify the number of<br />

participants. In the sample, this number is 3 because there are two created tasks, <strong>and</strong> the Main() method<br />

itself is a participant as well. Using a TaskFactory, two tasks are created to fork the iteration through the<br />

collection into two parts. After starting the tasks, using SignalAndWait(), the main method signals its<br />

completion <strong>and</strong> waits until all remaining participants either signal the completion or remove themselves as<br />

participants from the barrier. As soon as all participants are ready, the results from the tasks are taken <strong>and</strong><br />

zipped together with the Zip() extension method.<br />

static void Main()<br />

{<br />

const int numberTasks = 2;<br />

const int partitionSize = 1000000;<br />

var data = new List(FillData(partitionSize * numberTasks));<br />

readerWriterlockslim<br />

}<br />

var barrier = new Barrier(numberTasks + 1);<br />

var taskFactory = new TaskFactory();<br />

var tasks = new Task[numberTasks];<br />

for (int i = 0; i < participants; i++)<br />

{<br />

tasks[i] = taskFactory.StartNew(CalculationInTask,<br />

Tuple.Create(i, partitionSize, barrier, data));<br />

}<br />

barrier.SignalAndWait();<br />

var resultCollection = tasks[0].Result.Zip(tasks[1].Result, (c1, c2) =<br />

{<br />

return c1 + c2;<br />

});<br />

char ch = 'a';<br />

int sum = 0;<br />

foreach (var x in resultCollection)<br />

{<br />

Console.WriteLine("{0}, count: {1}", ch++, x);<br />

sum += x;<br />

}<br />

Console.WriteLine("main finished {0}", sum);<br />

Console.WriteLine("remaining {0}", barrier.ParticipantsRemaining);<br />

For a locking mechanism to allow multiple readers, but just one writer, for a resource, the class<br />

ReaderWriterLockSlim can be used. This class offers a locking functionality in which multiple readers can<br />

access the resource if no writer locked it, <strong>and</strong> only a single writer can lock the resource.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!