Threads in C# • This is a very brief introduction to using threads in C#; we will use Visual Studio 2008 • Many of these examples were taken from the online tutorial Threading in C# by Joseph Albahari • A link to this tutorial is http://www.albahari.com/threading/
23
Embed
Threads in C#blk/distributedComputing/Using... · 2009. 4. 27. · Threads in C# • This is a very brief introduction to using threads in C#; we will use Visual Studio 2008 • Many
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Threads in C#• This is a very brief introduction to using threads in C#; we will use Visual Studio 2008
• Many of these examples were taken from the online tutorial Threading in C# by Joseph Albahari
• A link to this tutorial is
http://www.albahari.com/threading/p // / g/
A First Exampleclass ThreadTest {class ThreadTest {static void Main() {Thread t = new Thread(WriteY);t Start(); // Run WriteY on the new threadt.Start(); // Run WriteY on the new threadwhile (true) Console.Write ("x"); // Write 'x' forever
}}static void WriteY() {while (true) Console.Write ("y"); // Write 'y' foreverConsole.Write ( y ); // Write y forever
• This program prints• This program prints Forcibly Woken!
Using the Synchronization Attributei S tusing System;
using System.Threading;using System.Runtime.Remoting.Contexts;[Synchronization][ y ]public class AutoLock : ContextBoundObject {public void Demo() {Console.Write ("Start...");Thread Sleep (1000); // We can't be preempted hereThread.Sleep (1000); // We can't be preempted hereConsole.WriteLine ("end"); // thanks to automatic locking!
} }public class Test {public static void Main() {AutoLock safeInstance = new AutoLock();new Thread (safeInstance Demo) Start();// Call the Demonew Thread (safeInstance.Demo).Start();// Call the Demonew Thread (safeInstance.Demo).Start();// method 3 timessafeInstance.Demo(); // concurrently.
}}
• What will be printed by this program?
Mutual Exclusionl O AtATi Pl {class OneAtATimePlease {// Use a name unique to the application static Mutex mutex = new
Mutex (false "oreilly com OneAtATimeDemo");Mutex (false, oreilly.com OneAtATimeDemo );static void Main() { // Wait 5 seconds if contended if (!mutex.WaitOne (TimeSpan.FromSeconds (5), false))
{Console.WriteLine ("Another instance is running.);{Co so e. te e ( ot e sta ce s u g.);return;
}try {
Console.WriteLine ("Running - press Enter to exit");
Semaphoresl S h T t {class SemaphoreTest {static Semaphore s = new Semaphore (3, 3);// Available=3; Capacity=3static void Main() {static void Main() {for (int i = 0; i < 10; i++)
new Thread (Go).Start();}}static void Go() {
while (true) {s.WaitOne();Thread.Sleep (100);// Only 3 threads can get here at onces.Release();
}}}
WaitAny, WaitAll and SignalAndWaitI dditi t th S t d W itO th d th• In addition to the Set and WaitOne methods, there are three static methods on the WaitHandle class
• WaitHandle.WaitAny waits for any one of an array of wait handles; WaitHandle.WaitAll waits on all of the given handles
• SignalAndWait is perhaps the most useful: it calls WaitOne on one WaitHandle, while calling Set on another WaitHandle– The first thread does the following:
WaitHandle.SignalAndWait (wh1, wh2);
– While the second thread does the opposite:WaitHandle.SignalAndWait (wh2, wh1);
The Dining Philosopher• The dining table with five philosophers
0
l d
4 1salad
3 2
A First Attempt at a SolutionS th h ti k h th f ll i id th• Suppose the chopsticks have the following ids: the chopstick to the right of philosopher j is labeled j; th h ti k t th l ft i l b l d j+1 d (ithe chopstick to the left is labeled j+1 mod n (in our problem n = 5)
• Each philosopher j follows this routine after entering and sitting at the table: pick up the chopstick on the right; pickup the chopstick on the left; eat some salad; put down the chopstick on the right; put down the chopstick on the left; leave the dining room to go think
• As we have learned previously, this solution can deadlock
static void Main(string[] args){int numOfPhilosophers = 5;p ;Thread[] t = new Thread[numOfPhilosophers];Semaphore[] s = new Semaphore[numOfPhilosophers];for(int i = 0; i < numOfPhilosophers; i++) {
//Semaphore(starting num of permits,total num of permits)s[i] = new Semaphore(1, 1);
}DiningPhilosophersMain phil = new DiningPhilosophersMain();DiningPhilosophersMain phil = new DiningPhilosophersMain();for(int i = 0; i < numOfPhilosophers; i++){t[i] = new Thread(phil.start);t[i].Start(new DiningPhilosopher[ ] ( g p
(i, new Random().Next(500), s, numOfPhilosophers));}Thread.Sleep(10000);S t C l W it Li ("All th d d ")System.Console.WriteLine("All threads done.");Environment.Exit(0);
think(philosopher);(p p );acquireChopstick(right(philosopher.id, philosopher), philosopher);Thread.Sleep(500); // this will cause deadlockacquireChopstick(left(philosopher.id, philosopher), philosopher);eat(philosopher);releaseChopstick(right(philosopher.id, philosopher), philosopher);releaseChopstick(left(philosopher.id, philosopher), philosopher);
}}}
private void acquireChopstick(int i, DiningPhilosopher philosopher){p q p ( , g p p p ){philosopher.chopsticks[i].WaitOne();System.Console.WriteLine("Philosopher " + philosopher.id +
" is picking up chopstick " + i);}
C# Implementation ‐ 3private void releaseChopstick(int i DiningPhilosopher philosopher){private void releaseChopstick(int i, DiningPhilosopher philosopher){
C# Implementation ‐ 4private int right(int i, DiningPhilosopher philosopher) {private int right(int i, DiningPhilosopher philosopher) {
return (i++) % philosopher.numOfPhils;}private int left(int i, DiningPhilosopher philosopher) {
return (philosopher.numOfPhils + i - 1) % philosopher.numOfPhils;}
}l Di i Phil h {class DiningPhilosopher {public int id { get; set; }public int sleep { get; set; }public Semaphore[] chopsticks { get; set; }p p [] p { g ; ; }public int numOfPhils { get; set; }public DiningPhilosopher(int id, int sleep, Semaphore[] chopsticks,
Limiting Access to the Dining Room• A simple solution to the possible starvation problem with the dining philosophers is to limited access to the dining room to n‐1 philosophers
• Suppose the semaphore diningroom has been initialized to n‐1 then the philosopher would first request to enter the dining room via this counting semaphore then, after eating and putting down the chopsticks, would release the semaphore
In‐Class Lab Activity• Introduce a counting semaphore into the given dining philosopher program
• Verify that limiting the number of philosophers in the room to n‐1 breaks the deadlock caused by the delays introduced between pick up right fork and pick up left fork
• Verify that if n philosophers are allowed in the room then the deadlock reappearspp
• This lab activity is described in more detail on a separate lab sheetseparate lab sheet