15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

}<br />

items[i]++;<br />

Thread.Sleep(50);<br />

}<br />

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

}<br />

finally<br />

{<br />

rwl.ExitWriteLock();<br />

}<br />

static void Main()<br />

{<br />

var taskFactory = new TaskFactory(TaskCreationOptions.LongRunning,<br />

TaskContinuationOptions.None);<br />

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

tasks[0] = taskFactory.StartNew(WriterMethod, 1);<br />

tasks[1] = taskFactory.StartNew(ReaderMethod, 1);<br />

tasks[2] = taskFactory.StartNew(ReaderMethod, 2);<br />

tasks[3] = taskFactory.StartNew(WriterMethod, 2);<br />

tasks[4] = taskFactory.StartNew(ReaderMethod, 3);<br />

tasks[5] = taskFactory.StartNew(ReaderMethod, 4);<br />

}<br />

}<br />

}<br />

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

{<br />

tasks[i].Wait();<br />

}<br />

code snippet ReaderWriterSample/Program.cs<br />

With a run of the application here, the first writer gets the lock first. The second writer <strong>and</strong> all readers need<br />

to wait. Next, the readers can work concurrently, while the second writer still waits for the resource.<br />

Writer 1 acquired the lock<br />

Writer 2 waiting for the write lock<br />

current reader count: 0<br />

Writer 2 waiting for the write lock<br />

current reader count: 0<br />

Writer 2 waiting for the write lock<br />

current reader count: 0<br />

Writer 2 waiting for the write lock<br />

current reader count: 0<br />

Writer 1 finished<br />

reader 4, loop: 0, item: 1<br />

reader 1, loop: 0, item: 1<br />

Writer 2 waiting for the write lock<br />

current reader count: 4<br />

reader 2, loop: 0, item: 1<br />

reader 3, loop: 0, item: 1<br />

reader 4, loop: 1, item: 2<br />

reader 1, loop: 1, item: 2<br />

reader 3, loop: 1, item: 2<br />

reader 2, loop: 1, item: 2<br />

Writer 2 waiting for the write lock<br />

current reader count: 4<br />

reader 4, loop: 2, item: 3<br />

reader 1, loop: 2, item: 3<br />

reader 2, loop: 2, item: 3<br />

reader 3, loop: 2, item: 3<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!