Microsoft Interview Question
Country: United States
Interview Type: In-Person
Both processes push the value of the local variable i to the shared location, without regard for what was there before. Henceforth, even though the memory updates are not atomic (as the destination address is not 32-bit or 64-bit word-aligned), the resulted value after SomeRunningFunction() finishes execution is 1000. Now, since the updates are not atomic we might expect spurious memory overwrites, but the limited range of values masks this flaw, as the high-order 16-bit word will always be 0, and it's only the low-order word that gets updated. Since the address is aligned to 16 bits, the 16-bit updates are this time atomic on the modern processors.
In this example, sleep(2000) acts effectively like a memory barrier, preventing both the compiler and the processor from excessively optimizing the memory writes. sleep(2000) is useful at reducing contention, but has no effect whatsoever on the final result. On both single core and multi core processors, the thread scheduling algorithms are able to make the context switches correctly, suspending the running threads in the middle even if in running state (as opposed to suspended, waiting for the sleep() to complete).
Hi Florian
Can sleep prohibit the compiler from optimizing. I have seen code like :
while(true) { sleep(0); }
to prevent compiler from removing the while loop completely.
But in this case I am curious if the compiler can optimize the code to something like :
void SomeRunningFunction()
{
for(int i = 1; i < 1000; ++i)
{
sleep(2000);
}
}
and setting *sharedmemoryaddress to 999 at compiler time.
On uniprocessor sleep may act as a way of synchronizing output from the two processes but that is not necessarily true Everytime in this scenario. On multiprocessor, the two processes can run on different cores and can execute in parallel doing the same thing means they might sleep at the same time. Overall the result after each loop is non deterministic and at the end will be 1000 when both processes are done.
Every process runs under their own address space and hence no overwriting can ever happen...
- Hj December 12, 2015So the answer is both processes will behave as if they were running in isolation..