Mutex 생성자

정의

Mutex 클래스의 새 인스턴스를 초기화합니다.

오버로드

Mutex()

기본 속성을 사용하여 Mutex 클래스의 새 인스턴스를 초기화합니다.

Mutex(Boolean)

호출한 스레드가 뮤텍스의 초기 소유권을 가져야 할지 여부를 나타내는 부울 값을 사용하여 Mutex 클래스의 새 인스턴스를 초기화합니다.

Mutex(Boolean, String)

호출 스레드가 뮤텍스의 초기 소유권을 가져야 할지 여부를 나타내는 부울 값과 뮤텍스 이름인 문자열을 사용하여 Mutex 클래스의 새 인스턴스를 초기화합니다.

Mutex(Boolean, String, Boolean)

호출한 스레드가 뮤텍스의 초기 소유권을 가져야 할지를 나타내는 부울 값, 뮤텍스의 이름인 문자열 및 메서드에서 반환할 때 호출한 스레드에 뮤텍스의 초기 소유권이 부여되었는지를 나타내는 부울 값을 사용하여 Mutex 클래스의 새 인스턴스를 초기화합니다.

Mutex(Boolean, String, Boolean, MutexSecurity)

호출한 스레드가 뮤텍스의 초기 소유권을 가져야 할지를 나타내는 부울 값, 뮤텍스의 이름인 문자열 및 메서드에서 반환할 때 호출한 스레드에 뮤텍스의 초기 소유권이 부여되었는지와 명명된 뮤텍스에 적용할 액세스 제어 보안을 나타내는 부울 변수를 사용하여 Mutex 클래스의 새 인스턴스를 초기화합니다.

Mutex()

Source:
Mutex.cs
Source:
Mutex.cs
Source:
Mutex.cs

기본 속성을 사용하여 Mutex 클래스의 새 인스턴스를 초기화합니다.

public:
 Mutex();
public Mutex ();
Public Sub New ()

예제

다음 코드 예제에서는 로컬 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.
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 Test13
{
    // 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

설명

이 생성자 오버로드를 호출하는 것은 생성자 오버로드를 Mutex(Boolean) 호출하고 뮤텍스의 초기 소유권을 지정하는 false 것과 동일합니다. 즉, 호출 스레드는 뮤텍스를 소유하지 않습니다.

추가 정보

적용 대상

Mutex(Boolean)

Source:
Mutex.cs
Source:
Mutex.cs
Source:
Mutex.cs

호출한 스레드가 뮤텍스의 초기 소유권을 가져야 할지 여부를 나타내는 부울 값을 사용하여 Mutex 클래스의 새 인스턴스를 초기화합니다.

public:
 Mutex(bool initiallyOwned);
public Mutex (bool initiallyOwned);
new System.Threading.Mutex : bool -> System.Threading.Mutex
Public Sub New (initiallyOwned As Boolean)

매개 변수

initiallyOwned
Boolean

호출한 스레드에 뮤텍스의 초기 소유권을 부여하면 true이고, 그렇지 않으면 false입니다.

예제

다음 코드 예제에서는 로컬 Mutex 개체를 사용하여 보호된 리소스에 대한 액세스를 동기화하는 방법을 보여줍니다. 를 만드는 스레드는 Mutex 처음에 소유합니다.

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 owns the
   // Mutex.
   static Mutex^ mut = gcnew Mutex( true );
   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()
{
   
   // Initialize the Mutex.
   Mutex^ mut = Test::mut;
   
   // 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();

   }
   
   // Wait one second before allowing other threads to
   // acquire the Mutex.
   Console::WriteLine( "Creating thread owns the Mutex." );
   Thread::Sleep( 1000 );
   Console::WriteLine( "Creating thread releases the Mutex.\r\n" );
   mut->ReleaseMutex();
}
// The example displays output like the following:
//       Creating thread owns the Mutex.
//       Creating thread releases the Mutex.
//       
//       Thread1 has entered the protected area
//       Thread1 is leaving the protected area
//       
//       Thread2 has entered the protected area
//       Thread2 is leaving the protected area
//       
//       Thread3 has entered the protected area
//       Thread3 is leaving the protected area
using System;
using System.Threading;

class Test
{
    private static Mutex mut;
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
    {
        // Create a new Mutex. The creating thread owns the Mutex.
        mut = new Mutex(true);
        // 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();
        }

        // Wait one second before allowing other threads to
        // acquire the Mutex.
        Console.WriteLine("Creating thread owns the Mutex.");
        Thread.Sleep(1000);

        Console.WriteLine("Creating thread releases the Mutex.\r\n");
        mut.ReleaseMutex();
    }

    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();
    }
}
// The example displays output like the following:
//       Creating thread owns the Mutex.
//       Creating thread releases the Mutex.
//       
//       Thread1 has entered the protected area
//       Thread1 is leaving the protected area
//       
//       Thread2 has entered the protected area
//       Thread2 is leaving the protected area
//       
//       Thread3 has entered the protected area
//       Thread3 is leaving the protected area
Imports System.Threading

Class Test
    ' Create a new Mutex. The creating thread owns the
    ' Mutex.
    Private Shared mut As New Mutex(True)
    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

        ' Wait one second before allowing other threads to
        ' acquire the Mutex.
        Console.WriteLine("Creating thread owns the Mutex.")
        Thread.Sleep(1000)

        Console.WriteLine("Creating thread releases the Mutex." & vbCrLf)
        mut.ReleaseMutex()
    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
' The example displays output like the following:
'       Creating thread owns the Mutex.
'       Creating thread releases the Mutex.
'       
'       Thread1 has entered the protected area
'       Thread1 is leaving the protected area
'       
'       Thread2 has entered the protected area
'       Thread2 is leaving the protected area
'       
'       Thread3 has entered the protected area
'       Thread3 is leaving the protected area

추가 정보

적용 대상

Mutex(Boolean, String)

Source:
Mutex.cs
Source:
Mutex.cs
Source:
Mutex.cs

호출 스레드가 뮤텍스의 초기 소유권을 가져야 할지 여부를 나타내는 부울 값과 뮤텍스 이름인 문자열을 사용하여 Mutex 클래스의 새 인스턴스를 초기화합니다.

public:
 Mutex(bool initiallyOwned, System::String ^ name);
[System.Security.SecurityCritical]
public Mutex (bool initiallyOwned, string name);
public Mutex (bool initiallyOwned, string? name);
public Mutex (bool initiallyOwned, string name);
[<System.Security.SecurityCritical>]
new System.Threading.Mutex : bool * string -> System.Threading.Mutex
new System.Threading.Mutex : bool * string -> System.Threading.Mutex
Public Sub New (initiallyOwned As Boolean, name As String)

매개 변수

initiallyOwned
Boolean

이 호출의 결과로 명명된 시스템 뮤텍스가 만들어지는 경우 호출한 스레드에 명명된 시스템 뮤텍스의 초기 소유권을 부여하려면 true이고, 그렇지 않으면 false입니다.

name
String

동기화 개체를 다른 프로세스와 공유할 예정이면 이름이고, 그렇지 않으면 null 또는 빈 문자열입니다. 이름은 대/소문자를 구분합니다. 백슬래시 문자(\)는 예약되어 있으며 네임스페이스를 지정하는 데만 사용할 수 있습니다. 네임스페이스에 대한 자세한 내용은 설명 섹션을 참조하세요. 운영 체제에 따라 이름에 대한 추가 제한이 있을 수 있습니다. 예를 들어 Unix 기반 운영 체제에서 네임스페이스를 제외한 후의 이름은 유효한 파일 이름이어야 합니다.

특성

예외

명명된 뮤텍스가 존재하고 이 뮤텍스에 액세스 제어 보안이 있지만, 사용자에게 FullControl이 없는 경우

name이 잘못되었습니다. 이유는 다양하며, 대표적인 이유는 운영 체제가 적용하는 일부 제한(예: 알 수 없는 접두사나 잘못된 문자)입니다. 이름 및 일반 접두사 "Global\" 및 "Local\"은 대/소문자를 구분합니다.

-또는-

다른 오류가 발생했습니다. HResult 속성에서 자세한 정보를 확인할 수 있습니다.

Windows에만 해당: name이 알 수 없는 네임스페이스를 지정했습니다. 자세한 내용은 개체 이름을 참조하세요.

name이 너무 깁니다. 길이 제한은 운영 체제나 구성에 따라 달라집니다.

이름이 name인 동기화 개체를 만들 수 없습니다. 다른 형식의 동기화 개체에 동일한 이름이 사용되었을 수 있습니다.

.NET Framework에만 해당: name이 MAX_PATH(260자)보다 깁니다.

예제

다음 예제에서는 명명된 뮤텍스를 사용하여 두 개의 별도 프로세스에서 실행되는 스레드 간에 신호를 전송하는 방법을 보여 줍니다.

둘 이상의 명령 창에서 이 프로그램을 실행합니다. 각 프로세스는 명명된 Mutex 뮤텍스 MyMutex를 나타내는 개체를 만듭니다. 명명된 뮤텍스는 수명을 나타내는 개체의 Mutex 수명으로 제한된 시스템 개체입니다. 명명된 뮤텍스는 첫 번째 프로세스가 개체를 Mutex 만들 때 만들어집니다. 이 예제에서 명명된 뮤텍스는 프로그램을 실행하는 첫 번째 프로세스가 소유합니다. 명명된 뮤텍스는 해당 뮤텍스를 나타내는 모든 개체가 Mutex 해제되면 제거됩니다.

이 예제에 사용된 생성자 오버로드는 명명된 뮤텍스의 초기 소유권이 부여되었는지 여부를 호출 스레드에 알릴 수 없습니다. 스레드가 명명된 뮤텍스를 만들 것이라고 확신할 수 없는 한 이 생성자를 사용하여 초기 소유권을 요청하면 안 됩니다.

using namespace System;
using namespace System::Threading;

int main()
{
   // Create the named mutex. Only one system object named 
   // "MyMutex" can exist; the local Mutex object represents 
   // this system object, regardless of which process or thread
   // caused "MyMutex" to be created.
   Mutex^ m = gcnew Mutex( false,"MyMutex" );
   
   // Try to gain control of the named mutex. If the mutex is 
   // controlled by another thread, wait for it to be released.        
   Console::WriteLine(  "Waiting for the Mutex." );
   m->WaitOne();
   
   // Keep control of the mutex until the user presses
   // ENTER.
   Console::WriteLine( "This application owns the mutex. "
   "Press ENTER to release the mutex and exit." );
   Console::ReadLine();
   m->ReleaseMutex();
}
using System;
using System.Threading;

public class Test1
{
    public static void Main()
    {
        // Create the named mutex. Only one system object named 
        // "MyMutex" can exist; the local Mutex object represents 
        // this system object, regardless of which process or thread
        // caused "MyMutex" to be created.
        Mutex m = new Mutex(false, "MyMutex");
        
        // Try to gain control of the named mutex. If the mutex is 
        // controlled by another thread, wait for it to be released.        
        Console.WriteLine("Waiting for the Mutex.");
        m.WaitOne();

        // Keep control of the mutex until the user presses
        // ENTER.
        Console.WriteLine("This application owns the mutex. " +
            "Press ENTER to release the mutex and exit.");
        Console.ReadLine();

        m.ReleaseMutex();
    }
}
Imports System.Threading

Public Class Test
   Public Shared Sub Main()
      ' Create the named mutex. Only one system object named 
      ' "MyMutex" can exist; the local Mutex object represents 
      ' this system object, regardless of which process or thread
      ' caused "MyMutex" to be created.
      Dim m As New Mutex(False, "MyMutex")
      
      ' Try to gain control of the named mutex. If the mutex is 
      ' controlled by another thread, wait for it to be released.        
      Console.WriteLine("Waiting for the Mutex.")
      m.WaitOne()
      
      ' Keep control of the mutex until the user presses
      ' ENTER.
      Console.WriteLine("This application owns the mutex. " _
          & "Press ENTER to release the mutex and exit.")
      Console.ReadLine()
      
      m.ReleaseMutex()
   End Sub 
End Class

설명

name 접두사를 추가 Global\ 하거나 Local\ 네임스페이스를 지정할 수 있습니다. 네임스페이 Global 스를 지정하면 동기화 개체를 시스템의 모든 프로세스와 공유할 수 있습니다. Local 네임스페이스를 지정하면 네임스페이스가 지정되지 않은 경우에도 기본값으로 동기화 개체를 동일한 세션의 프로세스와 공유할 수 있습니다. Windows에서 세션은 로그인 세션이며 서비스는 일반적으로 다른 비대화형 세션에서 실행됩니다. Unix와 유사한 운영 체제에서 각 셸에는 자체 세션이 있습니다. 세션 로컬 동기화 개체는 모두 동일한 세션에서 실행되는 부모/자식 관계와 프로세스 간의 동기화에 적합할 수 있습니다. Windows의 동기화 개체 이름에 대한 자세한 내용은 개체 이름을 참조하세요.

name 제공되고 요청된 형식의 동기화 개체가 네임스페이스에 이미 있는 경우 기존 동기화 개체가 사용됩니다. 다른 형식의 동기화 개체가 네임스페이스에 WaitHandleCannotBeOpenedException 이미 있는 경우 이 throw됩니다. 그렇지 않으면 새 동기화 개체가 만들어집니다.

가 이 initiallyOwned 아닌 null 경우 name 호출 스레드는 true이 호출의 결과로 명명된 시스템 뮤텍스를 만든 경우에만 뮤텍스를 소유합니다. 명명된 시스템 뮤텍스가 만들어졌는지 여부를 결정하는 메커니즘이 없으므로 이 생성자 오버로드를 호출할 때 를 initiallyOwned 지정 false 하는 것이 좋습니다. 초기 소유권을 Mutex(Boolean, String, Boolean) 결정해야 하는 경우 생성자를 사용할 수 있습니다.

이 생성자는 명명된 Mutex 시스템 뮤텍스를 나타내는 개체를 초기화합니다. 동일한 명명된 시스템 뮤텍스를 나타내는 여러 Mutex 개체를 만들 수 있습니다.

명명된 뮤텍스가 액세스 제어 보안을 사용하여 이미 만들어졌으며 호출자에게 가 없 MutexRights.FullControl으면 예외가 throw됩니다. 스레드 작업을 동기화하는 데 필요한 권한만 사용하여 명명된 기존 뮤텍스를 열려면 메서드를 OpenExisting 참조하세요.

에 대해 또는 빈 문자열을 name지정 null 하면 생성자를 호출한 것처럼 로컬 뮤텍스가 Mutex(Boolean) 만들어집니다. 이 경우 는 createdNew 항상 true입니다.

시스템 전체이기 때문에 명명된 뮤텍스는 프로세스 경계를 넘어 리소스 사용을 조정하는 데 사용할 수 있습니다.

참고

터미널 서비스를 실행하는 서버에서 명명된 시스템 뮤텍스는 두 가지 수준의 가시성을 가질 수 있습니다. 이름이 접두 Global\사 로 시작하는 경우 모든 터미널 서버 세션에서 뮤텍스가 표시됩니다. 이름이 접두 Local\사 로 시작하는 경우 뮤텍스는 만들어진 터미널 서버 세션에서만 표시됩니다. 이 경우 동일한 이름의 별도의 뮤텍스가 서버의 다른 각 터미널 서버 세션에 있을 수 있습니다. 명명된 뮤텍스를 만들 때 접두사를 지정하지 않으면 접두사를 Local\사용합니다. 터미널 서버 세션 내에서 이름이 접두사만 다른 두 개의 뮤텍스는 별도의 뮤텍스이며 둘 다 터미널 서버 세션의 모든 프로세스에 표시됩니다. 즉, 접두사 이름과 Global\Local\ 프로세스에 상대적이지 않고 터미널 서버 세션을 기준으로 뮤텍스 이름의 scope 설명합니다.

주의

기본적으로 명명된 뮤텍스는 해당 뮤텍스를 만든 사용자로 제한되지 않습니다. 다른 사용자는 뮤텍스를 입력하고 종료하지 않음으로써 뮤텍스를 방해하는 것을 포함하여 뮤텍스를 열고 사용할 수 있습니다. Unix와 유사한 운영 체제에서 파일 시스템은 명명된 뮤텍스 구현에 사용되며, 다른 사용자는 더 중요한 방법으로 명명된 뮤텍스를 방해할 수 있습니다. Windows에서 특정 사용자에 대한 액세스를 제한하려면 생성자 오버로드를 사용하거나 MutexAcl 명명된 뮤텍스를 MutexSecurity 만들 때 을 전달할 수 있습니다. Unix와 유사한 운영 체제에서는 현재 명명된 뮤텍스에 대한 액세스를 제한할 방법이 없습니다. 신뢰할 수 없는 사용자가 코드를 실행 중일 수 있는 시스템에 대한 액세스 제한 없이 명명된 뮤텍스를 사용하지 마세요.

백슬래시(\)는 뮤텍스 이름의 예약 문자입니다. 터미널 서버 세션에서 뮤텍스 사용에 대한 메모에 지정된 경우를 제외하고 뮤텍스 이름에 백슬래시(\)를 사용하지 마세요. 그렇지 않으면 뮤텍스의 이름이 기존 파일을 나타내더라도 DirectoryNotFoundException이 throw될 수 있습니다.

추가 정보

적용 대상

Mutex(Boolean, String, Boolean)

Source:
Mutex.cs
Source:
Mutex.cs
Source:
Mutex.cs

호출한 스레드가 뮤텍스의 초기 소유권을 가져야 할지를 나타내는 부울 값, 뮤텍스의 이름인 문자열 및 메서드에서 반환할 때 호출한 스레드에 뮤텍스의 초기 소유권이 부여되었는지를 나타내는 부울 값을 사용하여 Mutex 클래스의 새 인스턴스를 초기화합니다.

public:
 Mutex(bool initiallyOwned, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew);
[System.Security.SecurityCritical]
public Mutex (bool initiallyOwned, string name, out bool createdNew);
public Mutex (bool initiallyOwned, string? name, out bool createdNew);
public Mutex (bool initiallyOwned, string name, out bool createdNew);
[<System.Security.SecurityCritical>]
new System.Threading.Mutex : bool * string * bool -> System.Threading.Mutex
new System.Threading.Mutex : bool * string * bool -> System.Threading.Mutex
Public Sub New (initiallyOwned As Boolean, name As String, ByRef createdNew As Boolean)

매개 변수

initiallyOwned
Boolean

이 호출의 결과로 명명된 시스템 뮤텍스가 만들어지는 경우 호출한 스레드에 명명된 시스템 뮤텍스의 초기 소유권을 부여하려면 true이고, 그렇지 않으면 false입니다.

name
String

동기화 개체를 다른 프로세스와 공유할 예정이면 이름이고, 그렇지 않으면 null 또는 빈 문자열입니다. 이름은 대/소문자를 구분합니다. 백슬래시 문자(\)는 예약되어 있으며 네임스페이스를 지정하는 데만 사용할 수 있습니다. 네임스페이스에 대한 자세한 내용은 설명 섹션을 참조하세요. 운영 체제에 따라 이름에 대한 추가 제한이 있을 수 있습니다. 예를 들어 Unix 기반 운영 체제에서 네임스페이스를 제외한 후의 이름은 유효한 파일 이름이어야 합니다.

createdNew
Boolean

이 메서드가 반환될 때 로컬 뮤텍스가 만들어진 경우(즉, name이(가) null이거나 빈 문자열인 경우)나 지정된 명명된 시스템 뮤텍스가 만들어진 경우에는 true인 부울이 포함되고, 지정된 명명된 시스템 뮤텍스가 이미 있는 경우에는 false이(가) 포함됩니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다.

특성

예외

명명된 뮤텍스가 존재하고 이 뮤텍스에 액세스 제어 보안이 있지만, 사용자에게 FullControl이 없는 경우

name이 잘못되었습니다. 이유는 다양하며, 대표적인 이유는 운영 체제가 적용하는 일부 제한(예: 알 수 없는 접두사나 잘못된 문자)입니다. 이름 및 일반 접두사 "Global\" 및 "Local\"은 대/소문자를 구분합니다.

-또는-

다른 오류가 발생했습니다. HResult 속성에서 자세한 정보를 확인할 수 있습니다.

Windows에만 해당: name이 알 수 없는 네임스페이스를 지정했습니다. 자세한 내용은 개체 이름을 참조하세요.

name이 너무 깁니다. 길이 제한은 운영 체제나 구성에 따라 달라집니다.

이름이 name인 동기화 개체를 만들 수 없습니다. 다른 형식의 동기화 개체에 동일한 이름이 사용되었을 수 있습니다.

.NET Framework에만 해당: name이 MAX_PATH(260자)보다 깁니다.

예제

다음 코드 예제에서는 명명된 뮤텍스를 사용하여 프로세스 또는 스레드 간에 신호를 전송하는 방법을 보여 줍니다. 둘 이상의 명령 창에서 이 프로그램을 실행합니다. 각 프로세스는 명명된 Mutex 뮤텍스 "MyMutex"를 나타내는 개체를 만듭니다. 명명된 뮤텍스는 시스템 개체입니다. 이 예제에서 해당 수명은 해당 수명을 나타내는 개체의 수명으로 Mutex 제한됩니다. 명명된 뮤텍스는 첫 번째 프로세스가 로컬 Mutex 개체를 만들 때 만들어지고 이를 나타내는 모든 Mutex 개체가 해제될 때 제거됩니다. 명명된 뮤텍스는 처음에 첫 번째 프로세스에서 소유합니다. 두 번째 프로세스와 후속 프로세스는 이전 프로세스가 명명된 뮤텍스를 해제할 때까지 기다립니다.

// This example shows how a named mutex is used to signal between
// processes or threads.
// Run this program from two (or more) command windows. Each process
// creates a Mutex object that represents the named mutex "MyMutex".
// The named mutex is a system object whose lifetime is bounded by the
// lifetimes of the Mutex objects that represent it. The named mutex
// is created when the first process creates its local Mutex; in this
// example, the named mutex is owned by the first process. The named 
// mutex is destroyed when all the Mutex objects that represent it
// have been released. 
// The second process (and any subsequent process) waits for earlier
// processes to release the named mutex.
using namespace System;
using namespace System::Threading;
int main()
{
   
   // Set this variable to false if you do not want to request 
   // initial ownership of the named mutex.
   bool requestInitialOwnership = true;
   bool mutexWasCreated;
   
   // Request initial ownership of the named mutex by passing
   // true for the first parameter. Only one system object named 
   // "MyMutex" can exist; the local Mutex object represents 
   // this system object. If "MyMutex" is created by this call,
   // then mutexWasCreated contains true; otherwise, it contains
   // false.
   Mutex^ m = gcnew Mutex( requestInitialOwnership, "MyMutex", mutexWasCreated );
   
   // This thread owns the mutex only if it both requested 
   // initial ownership and created the named mutex. Otherwise,
   // it can request the named mutex by calling WaitOne.
   if (  !(requestInitialOwnership && mutexWasCreated) )
   {
      Console::WriteLine(  "Waiting for the named mutex." );
      m->WaitOne();
   }

   
   // Once the process has gained control of the named mutex,
   // hold onto it until the user presses ENTER.
   Console::WriteLine(  "This process owns the named mutex. "
    "Press ENTER to release the mutex and exit." );
   Console::ReadLine();
   
   // Call ReleaseMutex to allow other threads to gain control
   // of the named mutex. If you keep a reference to the local
   // Mutex, you can call WaitOne to request control of the 
   // named mutex.
   m->ReleaseMutex();
}
// This example shows how a named mutex is used to signal between
// processes or threads.
// Run this program from two (or more) command windows. Each process
// creates a Mutex object that represents the named mutex "MyMutex".
// The named mutex is a system object whose lifetime is bounded by the
// lifetimes of the Mutex objects that represent it. The named mutex
// is created when the first process creates its local Mutex; in this
// example, the named mutex is owned by the first process. The named 
// mutex is destroyed when all the Mutex objects that represent it
// have been released. 
// The second process (and any subsequent process) waits for earlier
// processes to release the named mutex.

using System;
using System.Threading;

public class Test12
{
    public static void Main()
    {
        // Set this variable to false if you do not want to request 
        // initial ownership of the named mutex.
        bool requestInitialOwnership = true;
        bool mutexWasCreated;

        // Request initial ownership of the named mutex by passing
        // true for the first parameter. Only one system object named 
        // "MyMutex" can exist; the local Mutex object represents 
        // this system object. If "MyMutex" is created by this call,
        // then mutexWasCreated contains true; otherwise, it contains
        // false.
        Mutex m = new Mutex(requestInitialOwnership, 
                            "MyMutex", 
                            out mutexWasCreated);
        
        // This thread owns the mutex only if it both requested 
        // initial ownership and created the named mutex. Otherwise,
        // it can request the named mutex by calling WaitOne.
        if (!(requestInitialOwnership && mutexWasCreated))
        {
            Console.WriteLine("Waiting for the named mutex.");
            m.WaitOne();
        }

        // Once the process has gained control of the named mutex,
        // hold onto it until the user presses ENTER.
        Console.WriteLine("This process owns the named mutex. " +
            "Press ENTER to release the mutex and exit.");
        Console.ReadLine();

        // Call ReleaseMutex to allow other threads to gain control
        // of the named mutex. If you keep a reference to the local
        // Mutex, you can call WaitOne to request control of the 
        // named mutex.
        m.ReleaseMutex();
    }
}
' This example shows how a named mutex is used to signal between
' processes or threads.
' Run this program from two (or more) command windows. Each process
' creates a Mutex object that represents the named mutex "MyMutex".
' The named mutex is a system object whose lifetime is bounded by the
' lifetimes of the Mutex objects that represent it. The named mutex
' is created when the first process creates its local Mutex; in this
' example, the named mutex is owned by the first process. The named 
' mutex is destroyed when all the Mutex objects that represent it
' have been released. 
' The second process (and any subsequent process) waits for earlier
' processes to release the named mutex.

Imports System.Threading

Public Class Test
   
   <MTAThread> _
   Public Shared Sub Main()
      ' Set this variable to false if you do not want to request 
      ' initial ownership of the named mutex.
      Dim requestInitialOwnership As Boolean = True
      Dim mutexWasCreated As Boolean
      
      ' Request initial ownership of the named mutex by passing
      ' true for the first parameter. Only one system object named 
      ' "MyMutex" can exist; the local Mutex object represents 
      ' this system object. If "MyMutex" is created by this call,
      ' then mutexWasCreated contains true; otherwise, it contains
      ' false.
      Dim m As New Mutex(requestInitialOwnership, "MyMutex", _
          mutexWasCreated)
      
      ' This thread owns the mutex only if it both requested 
      ' initial ownership and created the named mutex. Otherwise,
      ' it can request the named mutex by calling WaitOne.
      If Not (requestInitialOwnership And mutexWasCreated) Then
         Console.WriteLine("Waiting for the named mutex.")
         m.WaitOne()
      End If
      
      ' Once the process has gained control of the named mutex,
      ' hold onto it until the user presses ENTER.
      Console.WriteLine("This process owns the named mutex. " _
          & "Press ENTER to release the mutex and exit.")
      Console.ReadLine()
      
      ' Call ReleaseMutex to allow other threads to gain control
      ' of the named mutex. If you keep a reference to the local
      ' Mutex, you can call WaitOne to request control of the 
      ' named mutex.
      m.ReleaseMutex()
   End Sub
End Class

설명

name 접두사를 추가 Global\ 하거나 Local\ 네임스페이스를 지정할 수 있습니다. 네임스페이 Global 스를 지정하면 동기화 개체를 시스템의 모든 프로세스와 공유할 수 있습니다. Local 네임스페이스를 지정하면 네임스페이스가 지정되지 않은 경우에도 기본값으로 동기화 개체를 동일한 세션의 프로세스와 공유할 수 있습니다. Windows에서 세션은 로그인 세션이며 서비스는 일반적으로 다른 비대화형 세션에서 실행됩니다. Unix와 유사한 운영 체제에서 각 셸에는 자체 세션이 있습니다. 세션 로컬 동기화 개체는 모두 동일한 세션에서 실행되는 부모/자식 관계와 프로세스 간의 동기화에 적합할 수 있습니다. Windows의 동기화 개체 이름에 대한 자세한 내용은 개체 이름을 참조하세요.

name 제공되고 요청된 형식의 동기화 개체가 네임스페이스에 이미 있는 경우 기존 동기화 개체가 사용됩니다. 다른 형식의 동기화 개체가 네임스페이스에 WaitHandleCannotBeOpenedException 이미 있는 경우 이 throw됩니다. 그렇지 않으면 새 동기화 개체가 만들어집니다.

가 이 아니 nullinitiallyOwned 가 이면 name 호출 스레드는 true호출 후에 가 true 인 경우에만 createdNew 명명된 뮤텍스를 소유합니다. 그렇지 않으면 스레드가 메서드를 호출하여 뮤텍스를 WaitOne 요청할 수 있습니다.

이 생성자는 명명된 Mutex 시스템 뮤텍스를 나타내는 개체를 초기화합니다. 동일한 명명된 시스템 뮤텍스를 나타내는 여러 Mutex 개체를 만들 수 있습니다.

명명된 뮤텍스가 액세스 제어 보안을 사용하여 이미 만들어졌으며 호출자에게 권한이 없는 MutexRights.FullControl 경우 예외가 throw됩니다. 스레드 작업을 동기화하는 데 필요한 권한만 사용하여 명명된 기존 뮤텍스를 열려면 메서드를 OpenExisting 참조하세요.

에 대해 또는 빈 문자열을 name지정 null 하면 생성자를 호출한 것처럼 로컬 뮤텍스가 Mutex(Boolean) 만들어집니다. 이 경우 는 createdNew 항상 true입니다.

시스템 전체이기 때문에 명명된 뮤텍스는 프로세스 경계를 넘어 리소스 사용을 조정하는 데 사용할 수 있습니다.

참고

터미널 서비스를 실행하는 서버에서 명명된 시스템 뮤텍스는 두 가지 수준의 가시성을 가질 수 있습니다. 이름이 접두 Global\사 로 시작하는 경우 모든 터미널 서버 세션에서 뮤텍스가 표시됩니다. 이름이 접두 Local\사 로 시작하는 경우 뮤텍스는 만들어진 터미널 서버 세션에서만 표시됩니다. 이 경우 동일한 이름의 별도의 뮤텍스가 서버의 다른 각 터미널 서버 세션에 있을 수 있습니다. 명명된 뮤텍스를 만들 때 접두사를 지정하지 않으면 접두사를 Local\사용합니다. 터미널 서버 세션 내에서 이름이 접두사만 다른 두 개의 뮤텍스는 별도의 뮤텍스이며 둘 다 터미널 서버 세션의 모든 프로세스에 표시됩니다. 즉, 접두사 이름과 Global\Local\ 프로세스에 상대적이지 않고 터미널 서버 세션을 기준으로 뮤텍스 이름의 scope 설명합니다.

주의

기본적으로 명명된 뮤텍스는 해당 뮤텍스를 만든 사용자로 제한되지 않습니다. 다른 사용자는 뮤텍스를 입력하고 종료하지 않음으로써 뮤텍스를 방해하는 것을 포함하여 뮤텍스를 열고 사용할 수 있습니다. Unix와 유사한 운영 체제에서 파일 시스템은 명명된 뮤텍스 구현에 사용되며, 다른 사용자는 더 중요한 방법으로 명명된 뮤텍스를 방해할 수 있습니다. Windows에서 특정 사용자에 대한 액세스를 제한하려면 생성자 오버로드를 사용하거나 MutexAcl 명명된 뮤텍스를 MutexSecurity 만들 때 을 전달할 수 있습니다. Unix와 유사한 운영 체제에서는 현재 명명된 뮤텍스에 대한 액세스를 제한할 방법이 없습니다. 신뢰할 수 없는 사용자가 코드를 실행 중일 수 있는 시스템에 대한 액세스 제한 없이 명명된 뮤텍스를 사용하지 마세요.

백슬래시(\)는 뮤텍스 이름의 예약 문자입니다. 터미널 서버 세션에서 뮤텍스 사용에 대한 메모에 지정된 경우를 제외하고 뮤텍스 이름에 백슬래시(\)를 사용하지 마세요. 그렇지 않으면 뮤텍스의 이름이 기존 파일을 나타내더라도 DirectoryNotFoundException이 throw될 수 있습니다.

추가 정보

적용 대상

Mutex(Boolean, String, Boolean, MutexSecurity)

호출한 스레드가 뮤텍스의 초기 소유권을 가져야 할지를 나타내는 부울 값, 뮤텍스의 이름인 문자열 및 메서드에서 반환할 때 호출한 스레드에 뮤텍스의 초기 소유권이 부여되었는지와 명명된 뮤텍스에 적용할 액세스 제어 보안을 나타내는 부울 변수를 사용하여 Mutex 클래스의 새 인스턴스를 초기화합니다.

public:
 Mutex(bool initiallyOwned, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew, System::Security::AccessControl::MutexSecurity ^ mutexSecurity);
public Mutex (bool initiallyOwned, string name, out bool createdNew, System.Security.AccessControl.MutexSecurity mutexSecurity);
[System.Security.SecurityCritical]
public Mutex (bool initiallyOwned, string name, out bool createdNew, System.Security.AccessControl.MutexSecurity mutexSecurity);
new System.Threading.Mutex : bool * string * bool * System.Security.AccessControl.MutexSecurity -> System.Threading.Mutex
[<System.Security.SecurityCritical>]
new System.Threading.Mutex : bool * string * bool * System.Security.AccessControl.MutexSecurity -> System.Threading.Mutex
Public Sub New (initiallyOwned As Boolean, name As String, ByRef createdNew As Boolean, mutexSecurity As MutexSecurity)

매개 변수

initiallyOwned
Boolean

이 호출의 결과로 명명된 시스템 뮤텍스가 만들어지는 경우 호출한 스레드에 명명된 시스템 뮤텍스의 초기 소유권을 부여하려면 true이고, 그렇지 않으면 false입니다.

name
String

동기화 개체를 다른 프로세스와 공유할 예정이면 이름이고, 그렇지 않으면 null 또는 빈 문자열입니다. 이름은 대/소문자를 구분합니다. 백슬래시 문자(\)는 예약되어 있으며 네임스페이스를 지정하는 데만 사용할 수 있습니다. 네임스페이스에 대한 자세한 내용은 설명 섹션을 참조하세요. 운영 체제에 따라 이름에 대한 추가 제한이 있을 수 있습니다. 예를 들어 Unix 기반 운영 체제에서 네임스페이스를 제외한 후의 이름은 유효한 파일 이름이어야 합니다.

createdNew
Boolean

이 메서드가 반환될 때 로컬 뮤텍스가 만들어진 경우(즉, name이(가) null이거나 빈 문자열인 경우)나 지정된 명명된 시스템 뮤텍스가 만들어진 경우에는 true인 부울이 포함되고, 지정된 명명된 시스템 뮤텍스가 이미 있는 경우에는 false이(가) 포함됩니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다.

mutexSecurity
MutexSecurity

명명된 시스템 뮤텍스에 적용할 액세스 제어 보안을 나타내는 MutexSecurity 개체입니다.

특성

예외

name이 잘못되었습니다. 이유는 다양하며, 대표적인 이유는 운영 체제가 적용하는 일부 제한(예: 알 수 없는 접두사나 잘못된 문자)입니다. 이름 및 일반 접두사 "Global\" 및 "Local\"은 대/소문자를 구분합니다.

-또는-

다른 오류가 발생했습니다. HResult 속성에서 자세한 정보를 확인할 수 있습니다.

Windows에만 해당: name이 알 수 없는 네임스페이스를 지정했습니다. 자세한 내용은 개체 이름을 참조하세요.

name이 너무 깁니다. 길이 제한은 운영 체제나 구성에 따라 달라집니다.

명명된 뮤텍스가 존재하고 이 뮤텍스에 액세스 제어 보안이 있지만, 사용자에게 FullControl이 없는 경우

이름이 name인 동기화 개체를 만들 수 없습니다. 다른 형식의 동기화 개체에 동일한 이름이 사용되었을 수 있습니다.

.NET Framework에만 해당: name이 MAX_PATH(260자)보다 깁니다.

예제

다음 코드 예제에서는 액세스 제어 보안을 사용하여 명명된 뮤텍스의 교차 프로세스 동작을 보여 줍니다. 이 예제에서는 메서드 오버로드를 사용하여 OpenExisting(String) 명명된 뮤텍스가 있는지 테스트합니다.

뮤텍스가 없는 경우 현재 사용자에게 뮤텍스를 사용할 수 있는 권한을 거부하지만 뮤텍스에 대한 읽기 및 변경 권한을 부여하는 초기 소유권 및 액세스 제어 보안으로 만들어집니다.

두 명령 창에서 컴파일된 예제를 실행하는 경우 두 번째 복사본은 에 대한 호출 OpenExisting(String)에서 액세스 위반 예외를 throw합니다. 예외가 catch되고, 이 예제에서는 메서드 오버로드를 사용하여 OpenExisting(String, MutexRights) 사용 권한을 읽고 변경하는 데 필요한 권한으로 뮤텍스를 엽니다.

사용 권한이 변경되면 뮤텍스를 입력하고 해제하는 데 필요한 권한으로 뮤텍스가 열립니다. 세 번째 명령 창에서 컴파일된 예제를 실행하면 새 권한을 사용하여 실행됩니다.

using namespace System;
using namespace System::Threading;
using namespace System::Security::AccessControl;
using namespace System::Security::Permissions;

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand,Flags=SecurityPermissionFlag::UnmanagedCode)]
   static void Main()
   {
      String^ mutexName = L"MutexExample4";

      Mutex^ m = nullptr;
      bool doesNotExist = false;
      bool unauthorized = false;
      
      // The value of this variable is set by the mutex
      // constructor. It is true if the named system mutex was
      // created, and false if the named mutex already existed.
      //
      bool mutexWasCreated = false;

      // Attempt to open the named mutex.
      try
      {
         // Open the mutex with (MutexRights.Synchronize |
         // MutexRights.Modify), to enter and release the
         // named mutex.
         //
         m = Mutex::OpenExisting( mutexName );
      }
      catch ( WaitHandleCannotBeOpenedException^ ) 
      {
         Console::WriteLine( L"Mutex does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
         unauthorized = true;
      }

      // There are three cases: (1) The mutex does not exist.
      // (2) The mutex exists, but the current user doesn't
      // have access. (3) The mutex exists and the user has
      // access.
      //
      if ( doesNotExist )
      {
         // The mutex does not exist, so create it.
         // Create an access control list (ACL) that denies the
         // current user the right to enter or release the
         // mutex, but allows the right to read and change
         // security information for the mutex.
         //
         String^ user = String::Concat( Environment::UserDomainName, L"\\",
            Environment::UserName );
         MutexSecurity^ mSec = gcnew MutexSecurity;

         MutexAccessRule^ rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               MutexRights::Synchronize |
               MutexRights::Modify),
            AccessControlType::Deny );
         mSec->AddAccessRule( rule );

         rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               MutexRights::ReadPermissions |
                MutexRights::ChangePermissions),
            AccessControlType::Allow );
         mSec->AddAccessRule( rule );
         
         // Create a Mutex object that represents the system
         // mutex named by the constant 'mutexName', with
         // initial ownership for this thread, and with the
         // specified security access. The Boolean value that
         // indicates creation of the underlying system object
         // is placed in mutexWasCreated.
         //
         m = gcnew Mutex( true,mutexName, mutexWasCreated,mSec );
         
         // If the named system mutex was created, it can be
         // used by the current instance of this program, even
         // though the current user is denied access. The current
         // program owns the mutex. Otherwise, exit the program.
         //
         if ( mutexWasCreated )
         {
            Console::WriteLine( L"Created the mutex." );
         }
         else
         {
            Console::WriteLine( L"Unable to create the mutex." );
            return;
         }
      }
      else if ( unauthorized )
      {
         // Open the mutex to read and change the access control
         // security. The access control security defined above
         // allows the current user to do this.
         //
         try
         {
            m = Mutex::OpenExisting( mutexName,
               static_cast<MutexRights>(
                  MutexRights::ReadPermissions |
                  MutexRights::ChangePermissions) );
            
            // Get the current ACL. This requires
            // MutexRights.ReadPermissions.
            MutexSecurity^ mSec = m->GetAccessControl();

            String^ user = String::Concat( Environment::UserDomainName,
               L"\\", Environment::UserName );
            
            // First, the rule that denied the current user
            // the right to enter and release the mutex must
            // be removed.
            MutexAccessRule^ rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Deny );
            mSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Allow );
            mSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // MutexRights.ChangePermissions.
            m->SetAccessControl( mSec );

            Console::WriteLine( L"Updated mutex security." );
            
            // Open the mutex with (MutexRights.Synchronize
            // | MutexRights.Modify), the rights required to
            // enter and release the mutex.
            //
            m = Mutex::OpenExisting( mutexName );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine(
               L"Unable to change permissions: {0}", ex->Message );
            return;
         }
      }
      
      // If this program created the mutex, it already owns
      // the mutex.
      //
      if ( !mutexWasCreated )
      {
         // Enter the mutex, and hold it until the program
         // exits.
         //
         try
         {
            Console::WriteLine( L"Wait for the mutex." );
            m->WaitOne();
            Console::WriteLine( L"Entered the mutex." );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unauthorized access: {0}",
               ex->Message );
         }
      }

      Console::WriteLine( L"Press the Enter key to exit." );
      Console::ReadLine();
      m->ReleaseMutex();
      m->Dispose();
   }
};

int main()
{
   Example::Main();
}
using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string mutexName = "MutexExample4";

        Mutex m = null;
        bool doesNotExist = false;
        bool unauthorized = false;

        // The value of this variable is set by the mutex
        // constructor. It is true if the named system mutex was
        // created, and false if the named mutex already existed.
        //
        bool mutexWasCreated = false;

        // Attempt to open the named mutex.
        try
        {
            // Open the mutex with (MutexRights.Synchronize |
            // MutexRights.Modify), to enter and release the
            // named mutex.
            //
            m = Mutex.OpenExisting(mutexName);
        }
        catch(WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Mutex does not exist.");
            doesNotExist = true;
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The mutex does not exist.
        // (2) The mutex exists, but the current user doesn't 
        // have access. (3) The mutex exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The mutex does not exist, so create it.

            // Create an access control list (ACL) that denies the
            // current user the right to enter or release the 
            // mutex, but allows the right to read and change
            // security information for the mutex.
            //
            string user = Environment.UserDomainName + "\\"
                + Environment.UserName;
            var mSec = new MutexSecurity();

            MutexAccessRule rule = new MutexAccessRule(user, 
                MutexRights.Synchronize | MutexRights.Modify, 
                AccessControlType.Deny);
            mSec.AddAccessRule(rule);

            rule = new MutexAccessRule(user, 
                MutexRights.ReadPermissions | MutexRights.ChangePermissions,
                AccessControlType.Allow);
            mSec.AddAccessRule(rule);

            // Create a Mutex object that represents the system
            // mutex named by the constant 'mutexName', with
            // initial ownership for this thread, and with the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in mutexWasCreated.
            //
            m = new Mutex(true, mutexName, out mutexWasCreated, mSec);

            // If the named system mutex was created, it can be
            // used by the current instance of this program, even 
            // though the current user is denied access. The current
            // program owns the mutex. Otherwise, exit the program.
            // 
            if (mutexWasCreated)
            {
                Console.WriteLine("Created the mutex.");
            }
            else
            {
                Console.WriteLine("Unable to create the mutex.");
                return;
            }
        }
        else if (unauthorized)
        {
            // Open the mutex to read and change the access control
            // security. The access control security defined above
            // allows the current user to do this.
            //
            try
            {
                m = Mutex.OpenExisting(mutexName, 
                    MutexRights.ReadPermissions | MutexRights.ChangePermissions);

                // Get the current ACL. This requires 
                // MutexRights.ReadPermissions.
                MutexSecurity mSec = m.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\"
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the mutex must
                // be removed.
                MutexAccessRule rule = new MutexAccessRule(user, 
                     MutexRights.Synchronize | MutexRights.Modify,
                     AccessControlType.Deny);
                mSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new MutexAccessRule(user, 
                    MutexRights.Synchronize | MutexRights.Modify,
                    AccessControlType.Allow);
                mSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // MutexRights.ChangePermissions.
                m.SetAccessControl(mSec);

                Console.WriteLine("Updated mutex security.");

                // Open the mutex with (MutexRights.Synchronize 
                // | MutexRights.Modify), the rights required to
                // enter and release the mutex.
                //
                m = Mutex.OpenExisting(mutexName);
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
                    ex.Message);
                return;
            }
        }

        // If this program created the mutex, it already owns
        // the mutex.
        //
        if (!mutexWasCreated)
        {
            // Enter the mutex, and hold it until the program
            // exits.
            //
            try
            {
                Console.WriteLine("Wait for the mutex.");
                m.WaitOne();
                Console.WriteLine("Entered the mutex.");
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unauthorized access: {0}", ex.Message);
            }
        }

        Console.WriteLine("Press the Enter key to exit.");
        Console.ReadLine();
        m.ReleaseMutex();
        m.Dispose();
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const mutexName As String = "MutexExample4"

        Dim m As Mutex = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' The value of this variable is set by the mutex
        ' constructor. It is True if the named system mutex was
        ' created, and False if the named mutex already existed.
        '
        Dim mutexWasCreated As Boolean

        ' Attempt to open the named mutex.
        Try
            ' Open the mutex with (MutexRights.Synchronize Or
            ' MutexRights.Modify), to enter and release the
            ' named mutex.
            '
            m = Mutex.OpenExisting(mutexName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Mutex does not exist.")
            doesNotExist = True
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", ex.Message)
            unauthorized = True
        End Try

        ' There are three cases: (1) The mutex does not exist.
        ' (2) The mutex exists, but the current user doesn't 
        ' have access. (3) The mutex exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The mutex does not exist, so create it.

            ' Create an access control list (ACL) that denies the
            ' current user the right to enter or release the 
            ' mutex, but allows the right to read and change
            ' security information for the mutex.
            '
            Dim user As String = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim mSec As New MutexSecurity()

            Dim rule As New MutexAccessRule(user, _
                MutexRights.Synchronize Or MutexRights.Modify, _
                AccessControlType.Deny)
            mSec.AddAccessRule(rule)

            rule = New MutexAccessRule(user, _
                MutexRights.ReadPermissions Or _
                MutexRights.ChangePermissions, _
                AccessControlType.Allow)
            mSec.AddAccessRule(rule)

            ' Create a Mutex object that represents the system
            ' mutex named by the constant 'mutexName', with
            ' initial ownership for this thread, and with the
            ' specified security access. The Boolean value that 
            ' indicates creation of the underlying system object
            ' is placed in mutexWasCreated.
            '
            m = New Mutex(True, mutexName, mutexWasCreated, mSec)

            ' If the named system mutex was created, it can be
            ' used by the current instance of this program, even 
            ' though the current user is denied access. The current
            ' program owns the mutex. Otherwise, exit the program.
            ' 
            If mutexWasCreated Then
                Console.WriteLine("Created the mutex.")
            Else
                Console.WriteLine("Unable to create the mutex.")
                Return
            End If

        ElseIf unauthorized Then

            ' Open the mutex to read and change the access control
            ' security. The access control security defined above
            ' allows the current user to do this.
            '
            Try
                m = Mutex.OpenExisting(mutexName, _
                    MutexRights.ReadPermissions Or _
                    MutexRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' MutexRights.ReadPermissions.
                Dim mSec As MutexSecurity = m.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the mutex must
                ' be removed.
                Dim rule As New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Deny)
                mSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Allow)
                mSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' MutexRights.ChangePermissions.
                m.SetAccessControl(mSec)

                Console.WriteLine("Updated mutex security.")

                ' Open the mutex with (MutexRights.Synchronize 
                ' Or MutexRights.Modify), the rights required to
                ' enter and release the mutex.
                '
                m = Mutex.OpenExisting(mutexName)

            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unable to change permissions: {0}", _
                    ex.Message)
                Return
            End Try

        End If

        ' If this program created the mutex, it already owns
        ' the mutex.
        '
        If Not mutexWasCreated Then
            ' Enter the mutex, and hold it until the program
            ' exits.
            '
            Try
                Console.WriteLine("Wait for the mutex.")
                m.WaitOne()
                Console.WriteLine("Entered the mutex.")
            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unauthorized access: {0}", _
                    ex.Message)
            End Try
        End If

        Console.WriteLine("Press the Enter key to exit.")
        Console.ReadLine()
        m.ReleaseMutex()
        m.Dispose()
    End Sub 
End Class

설명

name 접두사를 추가 Global\ 하거나 Local\ 네임스페이스를 지정할 수 있습니다. 네임스페이 Global 스를 지정하면 동기화 개체를 시스템의 모든 프로세스와 공유할 수 있습니다. Local 네임스페이스를 지정하면 네임스페이스가 지정되지 않은 경우에도 기본값이 되며, 동기화 개체를 동일한 세션의 프로세스와 공유할 수 있습니다. Windows에서 세션은 로그인 세션이며 서비스는 일반적으로 다른 비대화형 세션에서 실행됩니다. Unix와 유사한 운영 체제에서 각 셸에는 자체 세션이 있습니다. 세션-로컬 동기화 개체는 모두 동일한 세션에서 실행되는 부모/자식 관계와 프로세스 간의 동기화에 적합할 수 있습니다. Windows의 동기화 개체 이름에 대한 자세한 내용은 개체 이름을 참조하세요.

name 제공되고 요청된 형식의 동기화 개체가 네임스페이스에 이미 있는 경우 기존 동기화 개체가 사용됩니다. 다른 형식의 동기화 개체가 네임스페이스에 이미 있는 경우 이 WaitHandleCannotBeOpenedException throw됩니다. 그렇지 않으면 새 동기화 개체가 만들어집니다.

가 이 아니 nullinitiallyOwned 이면 name 호출 스레드는 true호출 후 가 true 인 경우에만 createdNew 명명된 뮤텍스를 소유합니다. 그렇지 않으면 스레드가 메서드를 호출하여 뮤텍스를 WaitOne 요청할 수 있습니다.

이 생성자를 사용하여 만들 때 명명된 시스템 뮤텍스에 액세스 제어 보안을 적용하여 다른 코드가 뮤텍스를 제어하지 못하도록 합니다.

이 생성자는 명명된 Mutex 시스템 뮤텍스를 나타내는 개체를 초기화합니다. 동일한 명명된 시스템 뮤텍스를 나타내는 여러 Mutex 개체를 만들 수 있습니다.

명명된 시스템 뮤텍스가 없으면 지정된 액세스 제어 보안을 사용하여 만들어집니다. 명명된 뮤텍스가 있으면 지정된 액세스 제어 보안이 무시됩니다.

참고

호출자는 현재 사용자에게 일부 액세스 권한을 거부하거나 부여하지 않더라도 mutexSecurity 새로 만든 Mutex 개체를 완전히 제어할 수 있습니다. 그러나 현재 사용자가 생성자 또는 OpenExisting 메서드를 사용하여 동일한 명명된 뮤텍스를 나타내는 다른 Mutex 개체를 얻으려고 하면 Windows 액세스 제어 보안이 적용됩니다.

명명된 뮤텍스가 액세스 제어 보안을 사용하여 이미 만들어졌으며 호출자에게 이 없는 MutexRights.FullControl경우 예외가 throw됩니다. 스레드 활동을 동기화하는 데 필요한 권한만 있는 기존 명명된 뮤텍스를 열려면 메서드를 OpenExisting 참조하세요.

에 대해 또는 빈 문자열을 name지정 null 하면 생성자를 호출한 것처럼 로컬 뮤텍스가 Mutex(Boolean) 만들어집니다. 이 경우 는 createdNew 항상 true입니다.

시스템 전체이기 때문에 명명된 뮤텍스를 사용하여 프로세스 경계 간에 리소스 사용을 조정할 수 있습니다.

참고

터미널 서비스를 실행하는 서버에서 명명된 시스템 뮤텍스는 두 가지 수준의 가시성을 가질 수 있습니다. 이름이 접두 Global\사 로 시작하는 경우 모든 터미널 서버 세션에서 뮤텍스가 표시됩니다. 이름이 접두사 Local\로 시작하는 경우 뮤텍스는 만들어진 터미널 서버 세션에서만 표시됩니다. 이 경우 동일한 이름의 별도의 뮤텍스가 서버의 다른 각 터미널 서버 세션에 있을 수 있습니다. 명명된 뮤텍스를 만들 때 접두사를 지정하지 않으면 접두사 Local\가 필요합니다. 터미널 서버 세션 내에서 이름이 접두사만 다른 두 개의 뮤텍스는 별도의 뮤텍스이며 둘 다 터미널 서버 세션의 모든 프로세스에 표시됩니다. 즉, 접두사 이름과 Global\Local\ 프로세스에 상대적이지 않고 터미널 서버 세션을 기준으로 뮤텍스 이름의 scope 설명합니다.

주의

기본적으로 명명된 뮤텍스는 뮤텍스를 만든 사용자로 제한되지 않습니다. 다른 사용자는 뮤텍스를 입력하고 종료하지 않음으로써 뮤텍스를 방해하는 등 뮤텍스를 열고 사용할 수 있습니다. 특정 사용자에 대한 액세스를 제한하려면 명명된 뮤텍스를 MutexSecurity 만들 때 을 전달할 수 있습니다. 신뢰할 수 없는 사용자가 코드를 실행 중일 수 있는 시스템에 대한 액세스 제한 없이 명명된 뮤텍스를 사용하지 마세요.

백슬래시(\)는 뮤텍스 이름의 예약 문자입니다. 터미널 서버 세션에서 뮤텍스 사용에 대한 메모에 지정된 경우를 제외하고 뮤텍스 이름에 백슬래시(\)를 사용하지 마세요. 그렇지 않으면 뮤텍스의 이름이 기존 파일을 나타내더라도 DirectoryNotFoundException이 throw될 수 있습니다.

적용 대상