Here is a simple example:

Let us assume that two threads T1 and T2 each want to increment the value of a global integer by one. Ideally, the following sequence of operations would take place:

  1. Integer i = 0; (memory)
  2. T1 reads the value of i from memory into register1: 0
  3. T1 increments the value of i in register1: (register1 contents) + 1 = 1
  4. T1 stores the value of register1 in memory: 1
  5. T2 reads the value of i from memory into register2: 1
  6. T2 increments the value of i in register2: (register2 contents) + 1 = 2
  7. T2 stores the value of register2 in memory: 2
  8. Integer i = 2; (memory)

In the case shown above, the final value of i is 2, as expected. However, if the two threads run simultaneously without locking or synchronization, the outcome of the operation could be wrong. The alternative sequence of operations below demonstrates this scenario:

  1. Integer i = 0; (memory)
  2. T1 reads the value of i from memory into register1: 0
  3. T2 reads the value of i from memory into register2: 0
  4. T1 increments the value of i in register1: (register1 contents) + 1 = 1
  5. T2 increments the value of i in register2: (register2 contents) + 1 = 1
  6. T1 stores the value of register1 in memory: 1
  7. T2 stores the value of register2 in memory: 1
  8. Integer i = 1; (memory)

출처 : http://en.wikipedia.org/wiki/Race_condition#Computing

한줄요약 : 여러 쓰레드의 context-switch 순서 에 따라 값이 다를 수 있는 상황
저작자 표시 비영리 변경 금지
크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by Heart