This is an interview question.
class X
{
int i = 0 ;
public:
Class *foo()
{
for ( ; i < 1000 ; ++i )
{
// some code but do not change value of i
}
}
}
int main()
{
X myX ;
Thread t1 = create_thread( myX.foo() ) ;
Thread t2 = create_thread( myX.foo() ) ;
Start t1 ...
Start t2 ...
join(t1)
joint(t2)
}
Q1: if the code run on 1-cpu processor, how many times can the for-loop run in worst case?
Q2: what if the code run on 2-cpu processor, how many times can the for-loop run in worst case?
My ideas:
The loop may run infinite times, because a thread can run it many times before the other thread updates the value of i.
Or, when t1 is suspended, t2 runs 1000 times and then we have 1000 x 1000 times ?
Is this correct?
create_thread( myX.foo() )callscreate_threadwith the return value ofmyX.foo().myX.foo()is run on the main thread, somyX.iwill eventually have a value of 1000 (which is the value which it has after two calls tomyX.foo()).If the code was actually meant to run
myX.foo()twice on a two different threads concurrently, then the code would have undefined behaviour (due to the race condition in the access tomyX.i). So yes, the loop could run an infinite number of times (or zero times, or the program could decide to get up and eat a bagel).