Bon Thanh wrote:The variable i starts at 0. Any thread that starts will start by either incrementing i by 1 due to the if (i%10 != 0) condition or entering the for loop. Since the print statement is OUTSIDE of the for loop, every thread will have to increment i by a value of 9 before it can print it. Hence I don't see the values 0 to 8 being displayed.
I would agree with zero, but probably not agree with any other number... for example, here is how the number one would be printed.
1. Thread 1 runs first. Doesn't do anything at line 5. Does one loop. And context switches in the middle of incrementing the variable i, during reinitialization of the loop. Remember the post increment operator isn't atomic -- it is a read from memory, increment in register, and then write to memory. So... let's say it reads from memory, increments, but before it can write back to memory, a context switch occurs.
2. Thread 2 runs. Blah. Blah. Blah.
3. Thread 3 runs. Blah. Blah. Blah.
4. Thread X run. Blah. Blah. Blah. It finishes the loop, but before it load the variable from memory, to print the variable, it context switches.
5. Thread 1 runs again, and writes the one back to memory. Continues running, but context switches before it can change i again.
6. Thread X runs again, loads the variable (whose value is one) from memory, and prints it.
Henry