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
Loading
AndrewPosted May 10, 2009, 3:13 AM
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.
Kirtan PatelPosted May 10, 2009, 1:00 AM
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 :)