Mutex.ReleaseMutex 메서드

정의

Mutex을(를) 한 번 해제합니다.Releases the Mutex once.

public:
 void ReleaseMutex();
public void ReleaseMutex ();
member this.ReleaseMutex : unit -> unit
Public Sub ReleaseMutex ()

예외

호출 스레드가 뮤텍스를 소유하지 않습니다.The calling thread does not own the mutex.

현재 인스턴스가 이미 삭제된 경우The current instance has already been disposed.

예제

다음 예제에서는 로컬 Mutex 개체를 사용 하 여 보호 된 리소스에 대 한 액세스를 동기화 하는 방법을 보여 줍니다.The following example shows how a local Mutex object is used to synchronize access to a protected resource. 뮤텍스를 만드는 스레드는 소유 하지 않는 처음에 있습니다.The thread that creates the mutex does not own it initially. ReleaseMutex 메서드는 더 이상 필요 하지 않을 때 뮤텍스를 해제 하는 데 사용 됩니다.The ReleaseMutex method is used to release the mutex when it is no longer needed.

// 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.
 
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.
 
Imports System.Threading

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

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

    ' 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
End Class

설명

스레드가 뮤텍스를 가져올 때마다 (예를 들어 WaitOne 메서드를 호출 하 여) 뮤텍스의 소유권을 잃어 뮤텍스 소유권을 획득 하려고 시도 하는 다른 스레드의 차단을 해제 ReleaseMutex 해야 합니다.Whenever a thread acquires a mutex (for example, by calling its WaitOne method), it must subsequently call ReleaseMutex to relinquish ownership of the mutex and unblock other threads that are trying to gain ownership of the mutex. millisecondsTimeout 또는 timeout 매개 false 변수를 사용 하 여 WaitOne 메서드를 호출 하는 경우 요청 시간이 초과 되기 때문에 뮤텍스를 가져오지 못한 경우 스레드는 ReleaseMutex를 호출 하지 않아야 합니다 .이 경우에는 다음 예제와 같이 스레드에 의해 보호 되는 리소스에 대 한 액세스도 허용 하지 않아야 합니다.If the attempt to get ownership of the mutex fails (for example, when a call to the WaitOne method with a millisecondsTimeout or a timeout parameter returns false because the request times out), the thread shouldn't call ReleaseMutex, In this case, the thread should also not be allowed to access the resource protected by the mutex, as the following example shows.

using System;
using System.Threading;

class Example
{
    // 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()
    {
        Example ex = new Example();
        ex.StartThreads();
    }

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

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

    private static void ThreadProc()
    {
        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, and do not enter if the request times out.
        Console.WriteLine("{0} is requesting the mutex", Thread.CurrentThread.Name);
        if (mut.WaitOne(1000)) {
           Console.WriteLine("{0} has entered the protected area", 
               Thread.CurrentThread.Name);
   
           // Place code to access non-reentrant resources here.
   
           // Simulate some work.
           Thread.Sleep(5000);
   
           Console.WriteLine("{0} is leaving the protected area", 
               Thread.CurrentThread.Name);
   
           // Release the Mutex.
              mut.ReleaseMutex();
           Console.WriteLine("{0} has released the mutex", 
                             Thread.CurrentThread.Name);
        }
        else {
           Console.WriteLine("{0} will not acquire the mutex", 
                             Thread.CurrentThread.Name);
        }
    }

    ~Example()
    {
       mut.Dispose();
    }
}
// The example displays output like the following:
//       Thread1 is requesting the mutex
//       Thread1 has entered the protected area
//       Thread2 is requesting the mutex
//       Thread3 is requesting the mutex
//       Thread2 will not acquire the mutex
//       Thread3 will not acquire the mutex
//       Thread1 is leaving the protected area
//       Thread1 has released the mutex
Imports System.Threading

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

   Public Shared Sub Main()
      Dim ex As New Example()
      ex.StartThreads()
   End Sub
   
   Private Sub StartThreads()
        ' Create the threads that will use the protected resource.
        For i As Integer = 0 To numThreads - 1
            Dim newThread As New Thread(AddressOf ThreadProc)
            newThread.Name = String.Format("Thread{0}", i + 1)
            newThread.Start()
        Next

        ' The main thread returns to Main and exits, but the application continues to
        ' run until all foreground threads have exited.
   End Sub

   Private Sub ThreadProc()
        For i As Integer = 0 To numIterations - 1
            UseResource()
        Next
   End Sub

   ' This method represents a resource that must be synchronized
   ' so that only one thread at a time can enter.
   Private Sub UseResource()
        ' Wait until it is safe to enter.
        Console.WriteLine("{0} is requesting the mutex", 
                          Thread.CurrentThread.Name)
        If mut.WaitOne(1000) Then
           Console.WriteLine("{0} has entered the protected area", 
               Thread.CurrentThread.Name)
   
           ' Place code to access non-reentrant resources here.
   
           ' Simulate some work.
           Thread.Sleep(5000)
   
           Console.WriteLine("{0} is leaving the protected area", 
               Thread.CurrentThread.Name)
   
           ' Release the Mutex.
           mut.ReleaseMutex()
           Console.WriteLine("{0} has released the mutex", 
                             Thread.CurrentThread.Name)
        Else
           Console.WriteLine("{0} will not acquire the mutex", 
                             Thread.CurrentThread.Name)
        End If
   End Sub
   
   Protected Overrides Sub Finalize()
      mut.Dispose()
   End Sub
End Class
' The example displays output like the following:
'       Thread1 is requesting the mutex
'       Thread1 has entered the protected area
'       Thread2 is requesting the mutex
'       Thread3 is requesting the mutex
'       Thread2 will not acquire the mutex
'       Thread3 will not acquire the mutex
'       Thread1 is leaving the protected area
'       Thread1 has released the mutex

뮤텍스를 소유 하는 스레드 실행을 차단 하지 않고 반복된 대기 함수 호출에서 동일한 뮤텍스를 지정할 수 있습니다.A thread that owns a mutex can specify the same mutex in repeated wait function calls without blocking its execution. 공용 언어 런타임에 의해 호출 수가 유지 됩니다.The number of calls is kept by the common language runtime. 스레드는 뮤텍스의 소유권을 해제 하기 위해 동일한 횟수의 ReleaseMutex를 호출 해야 합니다.The thread must call ReleaseMutex the same number of times to release ownership of the mutex.

스레드가 뮤텍스를 소유 하는 동안 종료 하는 경우 뮤텍스는 중단 될 있다고 합니다.If a thread terminates while owning a mutex, the mutex is said to be abandoned. 뮤텍스의 상태를 signaled로 설정 되 고 대기 스레드는 소유권을 가져옵니다.The state of the mutex is set to signaled and the next waiting thread gets ownership. 뮤텍스를 소유 아무도 뮤텍스의 상태 신호입니다.If no one owns the mutex, the state of the mutex is signaled. .NET Framework 버전 2.0부터 뮤텍스를 획득 하는 다음 스레드에서 AbandonedMutexException throw 됩니다.Beginning in version 2.0 of the .NET Framework, an AbandonedMutexException is thrown in the next thread that acquires the mutex. 이전 버전의.NET Framework 2.0에서는 예외가 throw 되었습니다.Prior to version 2.0 of the .NET Framework, no exception was thrown.

주의

중단 된 뮤텍스는 종종 코드에서 심각한 오류를 나타냅니다.An abandoned mutex often indicates a serious error in the code. 스레드가 뮤텍스를 해제 하지 않고 종료 되 면 뮤텍스의 보호를 받는 데이터 구조 상태가 일관 되지 않을 수 있습니다.When a thread exits without releasing the mutex, the data structures protected by the mutex might not be in a consistent state. 뮤텍스의 소유권을 요청 하는 다음 스레드에서이 예외를 처리 하 고 데이터 구조의 무결성을 확인할 수 있으면 계속할 수 있습니다.The next thread to request ownership of the mutex can handle this exception and proceed, if the integrity of the data structures can be verified.

시스템 차원 뮤텍스의 경우 중단된 뮤텍스는 애플리케이션이 갑자기 종료되었음을 나타낼 수 있습니다(예: Windows 작업 관리자를 사용하여).In the case of a system-wide mutex, an abandoned mutex might indicate that an application has been terminated abruptly (for example, by using Windows Task Manager).

적용 대상

추가 정보