Hi all
it's my first time here and here's a question that I was asked yesterday
it's kind of pseudocode
____________________________________________
int globalVar = 0;
void Func() {
for (int i = 0; i < 10; i++)
globalVar = globalVar + 1;
}
void main() {
Thread x = new Thread(Func); x.Start();
Thread y = new Thread(Func); y.Start();
x.Join();
y.Join();
Write(globalVar);
}
____________________________________________
the final globalVar has values from 1 to 20.
I understand how it can be from 10 to 20, but
can you explain how can it be less than 10?
thanks
Question from interview
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.

Kirtan PatelRank #292 · 8.6K reputationPosted May 9, 2009, 9:00 PM EDT
public void Func()
{
for (int i = 0; i <5; i++)
{
Globalvar += 1;
}
}
and
void main()
{
Thread x = new Thread(Func);
Thread y = new Thread(Func);
x.Start();
x.Join();
y.Start();
Write(Globalvar);
}
thats it :)
Andrew3 reputationPosted May 9, 2009, 11:13 PM EDT
The question was about thread concurrency.
Two threads run the same code, that increments global variable 10 times each.
If both threads enter the critical section at the same time then final result would be 10 (instead of 20), but it can be even less than 10.
But I don't see how it can be so.