2

I read following thread unsafe example in page 871 of C# 7.0 in a Nutshell: The Definitive Reference.

    public class ThreadUnsafe
{
    static int val1=1, val2=1;

    public static void Go()
    {
        if (val2 != 0) Console.WriteLine(val1 / val2);
        val2 = 0;
    }
}
class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            ThreadPool.QueueUserWorkItem(x => ThreadUnsafe.Go());
        }

        ThreadUnsafe.Go();
        Console.WriteLine("Press any key for continuing...");
        Console.ReadKey();
    }
}

I have written a test program and launch 2 or more threads but cannot get the exception of division by zero.

I have also run this test program on my PC that have 4 core CPU and on 1 CPU VM, I also cannot get this exception of division by zero.

Could you help me that how can I run this sample code in thread unsafe and get the exception of division by zero?

Vulcan Lee
  • 493
  • 4
  • 8
  • 3
    Well, you'll need another thread that sets val2 to a non-zero value. And avoid using Console.WriteLine(), that is a function that internally takes a lock to serialize access to the console. Such locks have a knack for causing accidental synchronization. It is also *very* slow, further reducing the odds for a race. You just have to wait too long to see it go wrong. – Hans Passant Oct 30 '18 at 10:26
  • 1
    If your question is "I start 2 threads at the same time, both calling `Go` on the same object and I'm unable to reproduce a division-by-zero exception", then the reason for that is that the speed of your computer makes this **very** unlikely. Most likely, after you start the first thread, that thread manages to run this code to completion, before your second thread even starts. – Lasse V. Karlsen Oct 30 '18 at 10:28
  • @LasseVågsætherKarlsen is correct. – mjwills Oct 30 '18 at 11:50

0 Answers0