Home 9κ°• InterLocked
Post
Cancel

9κ°• InterLocked

9κ°• InterLocked

λΆ€μ œ: κ²½ν•© 쑰건 (Race condition)

곡유 λ³€μˆ˜ μ ‘κ·Όμ˜ 문제점

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Program{
	static int num = 0;
	static object obj = new object();

	static void Tread_1(){
		for(int i=0; i< 10000; i++){            
            num++;
		}
	}

    static void Tread_2(){

        for (int i=0; i<10000; i++){
            num--;
        }
    }
}

//...
//μŠ€λ ˆλ“œλ“€ μ‹€ν–‰μ‹œν‚€λŠ” ꡬ문

  • 10000λ²ˆμ”© 1μ”© λ”ν•˜κ³  1μ”© λΉΌλŠ” μ½”λ“œ
  • 결과둜 0이 λ‚˜μ˜¨λ‹€ (λ‚˜μ™€μ•Ό ν•œλ‹€) β‡’ ν•˜μ§€λ§Œ μ΄μƒν•œ 값이 λ‚˜μ˜€λ„€?
  • int number에 volatile ν‚€μ›Œλ“œλ₯Ό 뢙여도 λ˜‘κ°™μ΄ μ΄μƒν•œ 값이 λ‚˜μ˜΄

κ²½ν•© 쑰건

Race condition

μŠ€ν† λ¦¬μ™€ 비ꡐ

  1. μ†λ‹˜ 1λͺ…κ³Ό 직원 3λͺ…
  2. μ†λ‹˜μ΄ 콜라 ν•˜λ‚˜λ₯Ό μ£Όλ¬Έμ‹œν‚΄
  3. 직원 3λͺ…이 ν•˜λ‚˜μ”© 콜라λ₯Ό κ°€μ Έλ‹€μ€Œ
  4. μ†λ‹˜μ€ λ³„μ•ˆκ°„ μ½œλΌκ°€ 3개λ₯Ό λ°›κ²Œλ¨
  5. == κ²½ν•© 쑰건 λ°œμƒν•œ 것 !

++ μ—°μ‚°μžμ˜ μ‹€ν–‰ 원리

1
num++;

μœ„ μ½”λ“œμ˜ μ–΄μ…ˆλΈ”λ¦¬ μ½”λ“œμ—μ„œμ˜ μ‹€ν–‰ μ›λ¦¬λŠ” λ‹€μŒκ³Ό κ°™λ‹€

1
2
3
int tmp = num;
tmp += 1;
num = tmp;
      • 도 μœ„μ—μ„œ tmp -= 1; 일뿐 λ§ˆμ°¬κ°€μ§€μ΄λ‹€.

μŠ€λ ˆλ“œμ—μ„œ 이 μ½”λ“œκ°€ μ‹€ν–‰λ˜λŠ” 도쀑 경합이 μΌμ–΄λ‚˜κ²Œ λ˜μ–΄μ„œ μ΄μƒν•œ 값이 λ‚˜μ˜¨ 것 κ°™λ‹€.

Interlocked λ₯Ό μ΄μš©ν•œ 해결법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Program{
	static int num = 0;
	static object obj = new object();

	static void Tread_1(){
		for(int i=0; i< 10000; i++){

            Interlocked.Increment(ref num);

		}
	}

    static void Tread_2(){

        for (int i=0; i<10000; i++){
            Interlocked.Decrement(ref num);
        }
    }
}

// ...
//μŠ€λ ˆλ“œλ“€ μ‹€ν–‰μ‹œν‚€λŠ” ꡬ문
  • ++은 Interlocked.Incremnt(ref num)
      • 은 Interlocked.Decrement(ref num)
  • μŠ€λ ˆλ“œ 1κ³Ό 2의 (1) ++κ³Ό (2) - - μž‘μ—…μ΄ μ›μžμ μœΌλ‘œ μΌμ–΄λ‚˜κ²Œ λœλ‹€
  • μ›μžμ  := 순차적으둜 (1) μž‘μ—… 뒀에 (2) μž‘μ—…μ΄ μΌμ–΄λ‚˜κ²Œ λœλ‹€ (μˆœμ„œκ°€ 보μž₯됨)

Interlocked.increment (ref num) μ—μ„œ ref의 μ‚¬μš©

μ‹€μ œ num β€˜κ°’β€™μ΄ μ•„λ‹ˆλΌ num의 μ£Όμ†Œλ₯Ό κ°€μ Έμ™€μ„œ 레퍼런슀λ₯Ό μ‚¬μš©ν•¨

Interlock.Decrement () 의 단점

λŒ€λΆ€λΆ„ μ •μˆ˜λ§Œ μ‚¬μš©κ°€λŠ₯

μ‚¬μš©ν•  수 μžˆλŠ” 것이 ν•œμ •λ˜μ–΄ 있음

This post is licensed under CC BY 4.0 by the author.

10κ°• Lock 기초

11κ°• λ°λ“œλ½