다음을 통해 공유


Mutex 클래스

프로세스 간 동기화에 사용할 수도 있는 동기화 기본 형식입니다.

네임스페이스: System.Threading
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<ComVisibleAttribute(True)> _
Public NotInheritable Class Mutex
    Inherits WaitHandle
‘사용 방법
Dim instance As Mutex
[ComVisibleAttribute(true)] 
public sealed class Mutex : WaitHandle
[ComVisibleAttribute(true)] 
public ref class Mutex sealed : public WaitHandle
/** @attribute ComVisibleAttribute(true) */ 
public final class Mutex extends WaitHandle
ComVisibleAttribute(true) 
public final class Mutex extends WaitHandle

설명

참고

이 클래스에 적용되는 HostProtectionAttribute 특성의 Resources 속성 값은 Synchronization | ExternalThreading입니다. HostProtectionAttribute는 대개 아이콘을 두 번 클릭하거나, 명령을 입력하거나, 브라우저에서 URL을 입력하여 시작되는 데스크톱 응용 프로그램에 영향을 미치지 않습니다. 자세한 내용은 HostProtectionAttribute 클래스나 SQL Server 프로그래밍 및 호스트 보호 특성을 참조하십시오.

둘 이상의 스레드가 동시에 공유 리소스에 액세스해야 할 경우 한 번에 하나의 스레드가 리소스를 사용하도록 하는 동기화 메커니즘이 시스템에 필요합니다. Mutex는 공유 리소스에 대한 단독 액세스 권한을 하나의 스레드에만 부여하는 동기화 기본 형식입니다. 스레드가 뮤텍스를 가져오면 첫 번째 스레드가 뮤텍스를 해제할 때까지 해당 뮤텍스를 가져오려는 두 번째 스레드는 일시 중단됩니다.

WaitHandle.WaitOne 메서드를 사용하여 뮤텍스의 소유권을 요청할 수 있습니다. 뮤텍스를 소유하는 스레드는 뮤텍스의 실행을 차단하지 않고 WaitOne를 반복적으로 호출하여 같은 뮤텍스를 요청할 수 있습니다. 그러나 뮤텍스의 소유권을 해제하려면 스레드에서 ReleaseMutex 메서드를 같은 횟수만큼 호출해야 합니다. Mutex 클래스는 스레드 ID를 적용하므로 뮤텍스는 해당 뮤텍스를 가져온 스레드에서만 해제할 수 있습니다. 이와는 다르게 Semaphore 클래스는 스레드 ID를 적용하지 않습니다.

뮤텍스를 소유하고 있는 동안 스레드가 종료되면 뮤텍스가 중단됩니다. 뮤텍스 상태는 신호 받음으로 설정되고 대기 중인 다음 스레드가 소유권을 가져옵니다. 뮤텍스를 소유하는 스레드가 없는 경우 뮤텍스의 상태는 신호 받음으로 설정됩니다. .NET Framework 버전 2.0부터는 뮤텍스를 가져오는 다음 스레드에서 AbandonedMutexException이 throw됩니다. .NET Framework 2.0 이전 버전에서는 예외가 throw되지 않았습니다.

경고

뮤텍스가 중단되면 코드에 심각한 오류가 있는 것입니다. 뮤텍스를 해제하지 않고 스레드를 종료하면 뮤텍스가 보호하는 데이터 구조의 상태에 일관성이 없을 수 있습니다. 데이터 구조의 무결성을 확인할 수 있으면 뮤텍스의 소유권을 요청하는 다음 스레드가 이 예외를 처리한 다음 계속할 수 있습니다.

뮤텍스는 로컬 뮤텍스와 명명된 시스템 뮤텍스, 이렇게 두 가지 형식이 있습니다. 이름을 허용하는 생성자를 사용하여 Mutex 개체를 만들면 해당 이름의 운영 체제 개체에 연결됩니다. 명명된 시스템 뮤텍스는 운영 체제 전체에서 볼 수 있으며 프로세스 작업을 동기화하는 데 사용할 수 있습니다. 같은 명명된 시스템 뮤텍스를 나타내는 Mutex 개체를 여러 개 만들 수 있으며, OpenExisting 메서드를 사용하여 기존의 명명된 시스템 뮤텍스를 열 수 있습니다.

로컬 뮤텍스는 프로세스 내에만 있으며 로컬 Mutex 개체에 대한 참조가 있는 프로세스 내 스레드에서 사용할 수 있습니다. 각 Mutex 개체는 별도의 로컬 뮤텍스입니다.

예제

' This example shows how a Mutex is used to synchronize access
' to a protected resource. Unlike Monitor, Mutex can be used with
' WaitHandle.WaitAll and WaitAny, and can be passed across
' AppDomain boundaries.
 
Imports System
Imports System.Threading
Imports Microsoft.VisualBasic

Class Test
    ' Create a new Mutex. The creating thread does not own the
    ' Mutex.
    Private Shared mut As New Mutex()
    Private Const numIterations As Integer = 1
    Private Const numThreads As Integer = 3

    <MTAThread> _
    Shared Sub Main()
        ' Create the threads that will use the protected resource.
        Dim i As Integer
        For i = 1 To numThreads
            Dim myThread As New Thread(AddressOf MyThreadProc)
            myThread.Name = [String].Format("Thread{0}", i)
            myThread.Start()
        Next i

        ' The main thread exits, but the application continues to
        ' run until all foreground threads have exited.

    End Sub 'Main

    Private Shared Sub MyThreadProc()
        Dim i As Integer
        For i = 1 To numIterations
            UseResource()
        Next i
    End Sub 'MyThreadProc

    ' This method represents a resource that must be synchronized
    ' so that only one thread at a time can enter.
    Private Shared Sub UseResource()
        ' Wait until it is safe to enter.
        mut.WaitOne()

        Console.WriteLine("{0} has entered protected area", _
            Thread.CurrentThread.Name)

        ' Place code to access non-reentrant resources here.

        ' Simulate some work
        Thread.Sleep(500)

        Console.WriteLine("{0} is leaving protected area" & vbCrLf, _
            Thread.CurrentThread.Name)

        ' Release Mutex.
        mut.ReleaseMutex()
    End Sub 'UseResource
End Class 'MyMainClass
// This example shows how a Mutex is used to synchronize access
// to a protected resource. Unlike Monitor, Mutex can be used with
// WaitHandle.WaitAll and WaitAny, and can be passed across
// AppDomain boundaries.
 
using System;
using System.Threading;

class Test
{
    // Create a new Mutex. The creating thread does not own the
    // Mutex.
    private static Mutex mut = new Mutex();
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
    {
        // Create the threads that will use the protected resource.
        for(int i = 0; i < numThreads; i++)
        {
            Thread myThread = new Thread(new ThreadStart(MyThreadProc));
            myThread.Name = String.Format("Thread{0}", i + 1);
            myThread.Start();
        }

        // The main thread exits, but the application continues to
        // run until all foreground threads have exited.
    }

    private static void MyThreadProc()
    {
        for(int i = 0; i < numIterations; i++)
        {
            UseResource();
        }
    }

    // This method represents a resource that must be synchronized
    // so that only one thread at a time can enter.
    private static void UseResource()
    {
        // Wait until it is safe to enter.
        mut.WaitOne();

        Console.WriteLine("{0} has entered the protected area", 
            Thread.CurrentThread.Name);

        // Place code to access non-reentrant resources here.

        // Simulate some work.
        Thread.Sleep(500);

        Console.WriteLine("{0} is leaving the protected area\r\n", 
            Thread.CurrentThread.Name);
         
        // Release the Mutex.
        mut.ReleaseMutex();
    }
}
// This example shows how a Mutex is used to synchronize access
// to a protected resource. Unlike Monitor, Mutex can be used with
// WaitHandle.WaitAll and WaitAny, and can be passed across
// AppDomain boundaries.
using namespace System;
using namespace System::Threading;
const int numIterations = 1;
const int numThreads = 3;
ref class Test
{
public:

   // Create a new Mutex. The creating thread does not own the
   // Mutex.
   static Mutex^ mut = gcnew Mutex;
   static void MyThreadProc()
   {
      for ( int i = 0; i < numIterations; i++ )
      {
         UseResource();

      }
   }


private:

   // This method represents a resource that must be synchronized
   // so that only one thread at a time can enter.
   static void UseResource()
   {
      
      //Wait until it is OK to enter.
      mut->WaitOne();
      Console::WriteLine( "{0} has entered protected the area", Thread::CurrentThread->Name );
      
      // Place code to access non-reentrant resources here.
      // Simulate some work.
      Thread::Sleep( 500 );
      Console::WriteLine( "{0} is leaving protected the area\r\n", Thread::CurrentThread->Name );
      
      // Release the Mutex.
      mut->ReleaseMutex();
   }

};

int main()
{
   
   // Create the threads that will use the protected resource.
   for ( int i = 0; i < numThreads; i++ )
   {
      Thread^ myThread = gcnew Thread( gcnew ThreadStart( Test::MyThreadProc ) );
      myThread->Name = String::Format( "Thread {0}", i + 1 );
      myThread->Start();

   }
   
   // The main thread exits, but the application continues to 
   // run until all foreground threads have exited.
}
// This example shows how a Mutex is used to synchronize access
// to a protected resource. Unlike Monitor, Mutex can be used with
// WaitHandle.WaitAll and WaitAny, and can be passed across
// AppDomain boundaries.

import System.*;
import System.Threading.*;
import System.Threading.Thread;

class Test
{
    // Create a new Mutex. The creating thread does not own the
    // Mutex.
    private static Mutex mut = new Mutex();
    private static int numIterations = 1;
    private static int numThreads = 3;

    public static void main(String[] args)
    {
        // Create the threads that will use the protected resource.
        for (int i = 0; i < numThreads; i++) {
            Thread myThread = new Thread(new ThreadStart(MyThreadProc));
            myThread.set_Name(String.Format("Thread{0}", 
                String.valueOf(i + 1)));
            myThread.Start();
        }
    } //main

    // The main thread exits, but the application continues to
    // run until all foreground threads have exited.
    private static void MyThreadProc()
    {
        for (int i = 0; i < numIterations; i++) {
            UseResource();
        }
    } //MyThreadProc

    // This method represents a resource that must be synchronized
    // so that only one thread at a time can enter.
    private static void UseResource()
    {
        // Wait until it is safe to enter.
        mut.WaitOne();
        Console.WriteLine("{0} has entered the protected area", 
            Thread.get_CurrentThread().get_Name());

        // Place code to access non-reentrant resources here.
        // Simulate some work.
        Thread.Sleep(500);
        Console.WriteLine("{0} is leaving the protected area\r\n", 
            Thread.get_CurrentThread().get_Name());

        // Release the Mutex.
        mut.ReleaseMutex();
    } //UseResource
} //Test

상속 계층 구조

System.Object
   System.MarshalByRefObject
     System.Threading.WaitHandle
      System.Threading.Mutex

스레드로부터의 안전성

이 형식은 다중 스레드 작업을 수행하는 데 안전합니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

Mutex 멤버
System.Threading 네임스페이스
WaitHandle
Thread

기타 리소스

관리되는 스레딩
뮤텍스
관리되는 스레딩과 관리되지 않는 스레딩