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:
- Integer i = 0; (memory)
- T1 reads the value of i from memory into register1: 0
- T1 increments the value of i in register1: (register1 contents) + 1 = 1
- T1 stores the value of register1 in memory: 1
- T2 reads the value of i from memory into register2: 1
- T2 increments the value of i in register2: (register2 contents) + 1 = 2
- T2 stores the value of register2 in memory: 2
- 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:
- Integer i = 0; (memory)
- T1 reads the value of i from memory into register1: 0
- T2 reads the value of i from memory into register2: 0
- T1 increments the value of i in register1: (register1 contents) + 1 = 1
- T2 increments the value of i in register2: (register2 contents) + 1 = 1
- T1 stores the value of register1 in memory: 1
- T2 stores the value of register2 in memory: 1
- Integer i = 1; (memory)
출처 : http://en.wikipedia.org/wiki/Race_condition#Computing
한줄요약 : 여러 쓰레드의 context-switch 순서 에 따라 값이 다를 수 있는 상황
'Dev.Programming > Other.Computer.Science' 카테고리의 다른 글
| UTF-8 이 인코딩 중 선호되는 이유 (장점) (0) | 2010/04/20 |
|---|---|
| Process 와 Thread 의 차이점 (0) | 2010/04/20 |
| Race Condition 이란? (0) | 2010/04/20 |
| Spin Lock 이란? (0) | 2010/04/20 |
| Live Lock 이란? (0) | 2010/04/20 |
| 시스템 콜(System Call) 의 정의 및 STD C Lib. 와 구분하는 방법 (0) | 2010/04/20 |


