volatile(C# 참조)

volatile 키워드는 동시에 실행 중인 여러 스레드에 의해 필드가 수정될 수 있음을 나타냅니다. volatile로 선언된 필드에는 단일 스레드를 통한 액세스를 전제로 하는 컴파일러 최적화가 적용되지 않습니다. 이렇게 하면 필드의 값을 항상 최신 상태로 유지할 수 있습니다.

일반적으로 volatile 한정자는 액세스를 serialize할 때 lock 문을 사용하지 않고 여러 스레드에서 액세스하는 필드에 사용됩니다.

volatile 키워드는 다음과 같은 형식의 필드에 적용할 수 있습니다.

  • 참조 형식

  • 안전하지 않은 컨텍스트의 포인터 형식. 포인터 자체는 volatile일 수 있지만 포인터가 가리키는 개체는 volatile일 수 없습니다. 즉, "volatile 개체에 대한 포인터"를 선언할 수 없습니다.

  • sbyte, byte, short, ushort, int, uint, char, float 및 bool 같은 형식

  • 다음과 같은 기본 형식 중 하나를 사용하는 열거형 형식: byte, sbyte, short, ushort, int 또는 uint.

  • 참조 형식으로 알려진 제네릭 형식 매개 변수

  • IntPtrUIntPtr.

volatile 키워드는 클래스 또는 구조체의 필드에만 적용할 수 있습니다. 지역 변수는 volatile로 선언할 수 없습니다.

예제

다음 예제에서는 공용 필드 변수를 volatile로 선언하는 방법을 보여 줍니다.

    class VolatileTest
    {
        public volatile int i;

        public void Test(int _i)
        {
            i = _i;
        }
    }

다음 예제에서는 보조 또는 작업자 스레드를 만들고 기본 스레드와 함께 이 스레드를 병렬로 사용하여 작업 처리를 수행하는 방법을 보여 줍니다. 다중 스레딩에 대한 배경 정보는 관리되는 스레딩스레딩(C# 및 Visual Basic)을 참조하십시오.

using System;
using System.Threading;

public class Worker
{
    // This method is called when the thread is started.
    public void DoWork()
    {
        while (!_shouldStop)
        {
            Console.WriteLine("Worker thread: working...");
        }
        Console.WriteLine("Worker thread: terminating gracefully.");
    }
    public void RequestStop()
    {
        _shouldStop = true;
    }
    // Keyword volatile is used as a hint to the compiler that this data
    // member is accessed by multiple threads.
    private volatile bool _shouldStop;
}

public class WorkerThreadExample
{
    static void Main()
    {
        // Create the worker thread object. This does not start the thread.
        Worker workerObject = new Worker();
        Thread workerThread = new Thread(workerObject.DoWork);

        // Start the worker thread.
        workerThread.Start();
        Console.WriteLine("Main thread: starting worker thread...");

        // Loop until the worker thread activates.
        while (!workerThread.IsAlive) ;

        // Put the main thread to sleep for 1 millisecond to
        // allow the worker thread to do some work.
        Thread.Sleep(1);

        // Request that the worker thread stop itself.
        workerObject.RequestStop();

        // Use the Thread.Join method to block the current thread 
        // until the object's thread terminates.
        workerThread.Join();
        Console.WriteLine("Main thread: worker thread has terminated.");
    }
    // Sample output:
    // Main thread: starting worker thread...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: working...
    // Worker thread: terminating gracefully.
    // Main thread: worker thread has terminated.
}

C# 언어 사양

자세한 내용은 C# 언어 사양을 참조하십시오. 이 언어 사양은 C# 구문 및 사용법에 대한 신뢰할 수 있는 소스입니다.

참고 항목

참조

C# 키워드

한정자(C# 참조)

개념

C# 프로그래밍 가이드

기타 리소스

C# 참조