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]

... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12198정성태3/17/202011716오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202010871VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/20208824오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202010521.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202012860오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/20209518개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202011980개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202012318개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/20208514오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202013324개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202015506Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/20208259오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/20209348오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/20209990오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202011461오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/20209797오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
12182정성태3/11/202011044.NET Framework: 901. C# Windows Forms - Vista/7 이후의 Progress Bar 업데이트가 느린 문제파일 다운로드1
12181정성태3/11/202011880기타: 76. 재현 가능한 최소한의 예제 프로젝트란? - 두 번째 예제파일 다운로드1
12180정성태3/10/20208477오류 유형: 600. "Docker Desktop for Windows" - EXPOSE 포트가 LISTENING 되지 않는 문제
12179정성태3/10/202019865개발 환경 구성: 481. docker - PostgreSQL 컨테이너 실행
12178정성태3/10/202011343개발 환경 구성: 480. Linux 운영체제의 docker를 위한 tcp 바인딩 추가 [1]
12177정성태3/9/202011020개발 환경 구성: 479. docker - MySQL 컨테이너 실행
12176정성태3/9/202010440개발 환경 구성: 478. 파일의 (sha256 등의) 해시 값(checksum) 확인하는 방법
12175정성태3/8/202010521개발 환경 구성: 477. "Docker Desktop for Windows"의 "Linux Container" 모드를 위한 tcp 바인딩 추가
12174정성태3/7/202010067개발 환경 구성: 476. DockerDesktopVM의 파일 시스템 접근 [3]
12173정성태3/7/202011063개발 환경 구성: 475. docker - SQL Server 2019 컨테이너 실행 [1]
... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...