Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It is no matter on which type of system this code will run. Switching between threads goes in the same way. Worst case for all cases is: 1000 + 1000 * 999 * 998 * 997 * ... * 2 * 1 times. (incorrect!!! correct one is in update)</p> <p>When first thread tries to increase a variable (it already read a value, but not written yet), second thread can make all the loop from the start value of i, but when second thread finishing it's last loop, first thread increases a value of i, and second thread starts it's long job again :)</p> <p><em>*</em> Updated (A little more details)</p> <p>Sorry, real formula is:</p> <p>1000 + 1000 + 999 + 998 + ... + 2 + 1 times, or 500999</p> <p>Each iteration of the loop looks like this:</p> <ol> <li>Check condition.</li> <li>Make a work.</li> <li>Read value from i</li> <li>Increase read value</li> <li>Write value to i</li> </ol> <p>Nobody said that step 2 has constant time. So I suppose that it has a varying and suitable for my worst case time.</p> <p>Here is this worst case:</p> <p>Iteration 1:</p> <p>[1st thread] Makes steps 1-4 of the first loop iteration (very long work time)</p> <p>[2nd thread] Makes all the loop (1000 times), but doesn't check a condition last time</p> <p>Iteration 2:</p> <p>[1] Maskes step 5, so now i == 1, and makes steps 1-4 of next loop iteration</p> <p>[2] Makes all the loop from current i (999 times)</p> <p>Iteration 3: the same as before, but i == 2</p> <p>...</p> <p>Iteration 1000: the same as before , but i == 999</p> <p>In the end we will have 1000 Iterations and each iteration will have 1 execution of loop code from first thread and (1000 - Iteration number) executions from second thread.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload