Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

C# Unsafe Thread Monitoring?

How does the Monitoring class solve the unsafe thread problem in the following example:

class ThreadUnsafe {

static int val1, val2;

static void Go(){

if (val2 != 0) Console.WriteLine( val1 / val2);

val2=0;}

}

Update:

Monitor class I should say.

1 Answer

Relevance
  • ?
    Lv 5
    6 years ago

    The variable val2 is not local to the function Go(). So if more than one thread calls Go you could get a division by 0. For example:

    Thread 1: Does the test "if(val2 != 0)" but then it gets swapped out, and

    Thread 2: Is started, calls Go(), does the if, the write, and sets val2=0. Then Thread 2 gets swapped out and

    Thread 1 is restarted, it goes to do the "Console.WriteLine(val1/val2)" but since Thread 2 set val2 to 0, it gets a divide by 0 fault.

Still have questions? Get your answers by asking now.