Previous Section  < Day Day Up >  Next Section

13.5. Test Your Understanding


An asynchronous delegate must have a void return value.

  1. True

  2. False


Given this delegate

private delegate void myDelegate(string msg);

myDelegate d = new myDelegate(PrintMessage);

identify the role of ia, p1, p2, and p3 in this BeginInvoke call:

ia = d.BeginInvoke(p1, p2, p3);


What is thread local storage used for?


What is the default maximum number of threads that a thread pool can hold?


What two delegates are used to create a thread directly, and how do they differ?


Describe a syntactically simpler way to generate the following code:



   // Code to synchronize

} finally {




How many times does the following code print the console message?

private static s;

public static void Main()


   s = new Semaphore(0, 3);

   // Create and start five numbered threads

   for(int i = 1; i <= 5; i++)


      Thread t = new Thread(new ThreadStart(Worker));




private static void Worker(object num)



   Console.WriteLine("Thread enters semaphore  ");




  1. 0

  2. 1

  3. 3

  4. 5


What happens when you attempt to run this code?

class UseMutex


   public void ThreadStart()


      Mutex mutex = new Mutex(false, "MyMutex");


      Console.WriteLine("Worker Thread");


   static void Main()


      UseMutex obj = new UseMutex();

      Thread thread = new Thread(

            new ThreadStart(obj.ThreadStart));

      Mutex mutex = new Mutex(true, "MyMutex");



      Console.WriteLine("Primary Thread");




  1. It prints:

    Worker Thread
    Primary Thread

  2. It prints:

    Primary Thread
    Worker Thread

  3. The program deadlocks and there is no output.


To illustrate deadlocking, Edsger Dijkstra introduced a "Dining Philosopher" metaphor that has become a classical way of introducing resource allocation and deadlocking. The metaphor (with variations) goes like this:

Five philosophers, who spend their lives alternately thinking and eating, are sitting around a table. In the center of the round table is an infinite supply of food. Before each philosopher is a plate, and between each pair of plates is a single chopstick. Once a philosopher quits thinking, he or she attempts to eat. In order to eat, a philosopher must have possession of the chopstick to the left and right of the plate.

Your challenge is to design a program that creates five threads梠ne to represent each philosopher梩hat continually perform the tasks of thinking and eating. The program should implement a synchronization scheme that allows each thread to periodically acquire two chopsticks so that it can eat for a fixed or random (your choice) amount of time. After eating, a philosopher should release its chopsticks and think for a while before trying to eat again.

Hint: Use Monitor.Wait() to try to acquire chopsticks, and Monitor.PulseAll() to notify all threads that chopsticks are being released.

    Previous Section  < Day Day Up >  Next Section