Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - volatile 키워드로 인한 차이점을 발생시키는 예제

이전에 C++ 언어로 만든 volatile 예제를 실었는데요.

C++ volatile 키워드
; https://www.sysnet.pe.kr/2/0/413

아쉽게도 위의 예제를 C#으로 옮겨서 테스트해보면 volatile 유무에 따른 실행차이가 나지 않습니다. 그래도 ^^ 혹시나 싶어, 위의 C++ 예제를 살짝 변경해 다음과 같이 작성해 보니 차이점이 발생하긴 했습니다.

using System;
using System.Threading;

public class TestClass
{
    bool m_resultState;
    bool m_terminate;

    public void Start()
    {
        int k = 0;

        while (m_terminate == false)
        {
            Console.WriteLine(k++);
            Thread.Sleep(1000);
        }

        m_resultState = true;

        Console.WriteLine("m_resultState == " + m_resultState);
    }

    public void endThread()
    {
        m_terminate = true;

        while (true)
        {
            if (true == m_resultState)
            {
                Console.WriteLine("result() == true");
                break;
            }
        }
    }
}

public class WorkerThreadExample
{
    static void Main()
    {
        TestClass testClass = new TestClass();

        Thread t1 = new Thread(testClass.Start);
        t1.Start();
        Thread.Sleep(2000);

        testClass.endThread();
    }
}

위의 프로그램을 Release 모드로 컴파일해 실행하면 화면에 다음과 같이 출력한 후,

0
1
m_resultState == True

무한루프에 빠져 CPU 사용량이 "1/코어"만큼 올라갑니다. 코드를 살짝 보면, "m_resultState == True" 출력은 t1 스레드가 종료하기 바로 전이므로 t1 스레드는 무조건 없어졌다고 확신할 수 있고 출력 내용처럼 m_resultState 필드의 값은 True가 된 것이 맞습니다. 그런데도 endThread 메서드 내부의 result() 메서드는 (분명 이상하지만!) false를 반환하고 있기 때문에 무한 루프에 빠진 것입니다. (result 메서드는 최적화 과정에서 인라인화되었을 것입니다.)

반면 Debug 모드로 컴파일하거나, m_resultState 필드를 다음과 같이 volatile 예약어로 장식해주면 무한 루프 현상없이 프로그램이 잘 종료됩니다.

volatile bool m_resultState;

왜냐하면, volatile로 지정된 필드는 1) 최적화 대상에서 제외하며 2) 해당 값을 읽고/쓰는 코드에 대해 무조건 메모리에 직접 읽고/쓰는 동작으로 연결되기 때문입니다.

(첨부된 파일은 위의 코드를 재현할 수 있는 예제입니다.)
(참고로, 위의 코드는 어느 순간 CLR이 바뀌면 잘 동작할 수도 있습니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/22/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2019-01-22 09시48분
[hong]
0
1
m_resultState == True => this is fault. because you wrote the code Console.WriteLine("m_resultState == true");

I feel confused..

and i got another example....

if remove volatile keyword than the loop will never stop on release...

class Program
{
    public static volatile bool complete = false;

    private static void Main()
    {
        var t = new Thread(() =>
        {
            bool toggle = false;
            while (!complete) toggle = !toggle;
        });

        t.Start();
        Thread.Sleep(1000); //let the other thread spin up
        complete = true;
        t.Join(); // Blocks indefinitely when you remove volatile
    }
}
[guest]

1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...
NoWriterDateCnt.TitleFile(s)
13308정성태4/4/20234184스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20233939.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
13306정성태4/3/20233703Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
13305정성태4/1/20234078Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)파일 다운로드1
13304정성태3/31/20234422VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20233793Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234392Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234495Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20234138Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20233901Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20233896Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234564Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20233892Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20234166Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234338.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234402오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234516Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20234905.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234372.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233573Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233694Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20233861Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234292Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20233870Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20234095Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233644오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...