A function is thread safe if and only if it will

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: rrect instruction ordering. After each thread has updated the shared variable cnt, its value in memory is 2, which is the expected result. Step 1 2 3 4 5 6 7 8 9 10 Thread 1 1 1 1 2 2 2 2 2 1 Instr À½ Ľ ͽ ˽ À¾ ľ ; ˾ ̾ ̽ %eax½ – 0 1 1 – – – – – 1 %eax¾ – – – – – 1 2 2 2 – cnt 0 0 0 1 1 1 1 2 2 2 Step 1 2 3 4 5 6 7 8 9 10 Thread 1 1 1 2 2 1 1 2 2 2 Instr À½ Ľ ͽ À¾ ľ ˽ ̽ ; ˾ ̾ %eax½ – 0 1 – – 1 1 – – – %eax¾ – – – – 0 – – 1 1 1 cnt 0 0 0 0 0 1 1 1 1 1 (a) Correct ordering (b) Incorrect ordering Figure 11.10: Sequentially-consistent orderings for the first loop iteration in badcnt.c. 576 CHAPTER 11. CONCURRENT PROGRAMMING WITH THREADS On the other hand, the ordering in Figure 11.10(b) produces an incorrect value for cnt. The problem occurs because thread 2 loads cnt in step 5, after thread 1 loads cnt in step 2, but before thread 1 stores its updated value in step 6. Thus each thread ends up storing an updated counter valu...
View Full Document

Ask a homework question - tutors are online