abg
abg

Reputation: 2092

How to get thread results through local variables?

I am trying to get thread results through local variables.

There is the code:

static void Main() 
{   
    long res1 = 0, res2 = 0;

    long n1 = 5000, n2 = 10000; 

    Thread t1 = new Thread(() => 
    { 
        res1 = Factorial(n1); 
    }); 

    Thread t2 = new Thread(() => { res2=Factorial(n2); }); 

    t1.Start();  
    t2.Start(); 
    t1.Join();  
    t2.Join(); 

    Console.WriteLine("Factorial of {0} equals {1}", n1, res1); 
    Console.WriteLine("Factorial of {0} equals {1}", n2, res2); 
} 

Output:

Factorial of 5000 equals 0
Factorial of 10000 equals 0

Why does this code return 0?

This is the factorial function:

static long Factorial(long n) 
{ 
    long res = 1; 
    do 
    { 
        res = res * n; 
    } while(--n > 0); 

    return res; 
} 

Upvotes: 2

Views: 95

Answers (1)

i3arnon
i3arnon

Reputation: 116558

There's no problem with the use of threads or variable capturing. Your Factorial method simply returns 0 because res = res * n quickly overflows until these values are reached:

long res = -9223372036854775808;
long n = 4938;

Console.WriteLine(res * n);

You can see that the result is 0 and if we surround the calculation with checked we'll get an OverflowException:

long res = -9223372036854775808;
long n = 4938;

checked
{
    Console.WriteLine(res*n);
}

And of course if res becomes 0 once, any further multiplication would result in 0 as well.

I'm not sure what you're trying to calculate but you probably need a different (bigger) numerical data type (e.g. decimal)

Upvotes: 6

Related Questions