Thursday, 8 August 2013

Conflicting threads on a local variable

Conflicting threads on a local variable

why is it, that in the following code, n doesn't end up being 0, it's some
random number with a magnitude less than 1000000 each time, somtimes even
a negative number?
static void Main(string[] args)
{
int n = 0;
var up = new Thread(() =>
{
for (int i = 0; i < 1000000; i++)
{
n++;
}
});
up.Start();
for (int i = 0; i < 1000000; i++)
{
n--;
}
up.Join();
Console.WriteLine(n);
Console.ReadLine();
}
Doesn't up.Join() force both for loops to finish before WriteLine is called?
I understand that the local variable is actually part of a class behind
the scenes (think it's called a closure), however because the local
variable n is actually heap allocated, would that affect n not being 0
each time?

No comments:

Post a Comment