mutexとは? わかりやすく解説

Mutex クラス

同期プリミティブは、プロセス間の同期にも使用できます

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

<ComVisibleAttribute(True)> _
Public NotInheritable Class
 Mutex
    Inherits WaitHandle
[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
解説解説

ミューテックスには、ローカル ミューテックスと名前付システム ミューテックス2 種類あります。名前を受け入れコンストラクタ使用して 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
スレッド セーフスレッド セーフ

この型は、マルチスレッド操作に対して安全です。

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Mutex コンストラクタ ()

Mutex クラス新しインスタンス既定プロパティ使用して初期化します。

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

解説解説
使用例使用例

ローカル 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
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Mutex コンストラクタ (Boolean)

呼び出し元のスレッドミューテックス初期所有権があるかどうかを示す Boolean 型の値を使用して、Mutex クラス新しインスタンス初期化します。

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Sub New ( _
    initiallyOwned As Boolean _
)
Dim initiallyOwned As Boolean

Dim instance As New Mutex(initiallyOwned)
public Mutex (
    bool initiallyOwned
)
public:
Mutex (
    bool initiallyOwned
)
public Mutex (
    boolean initiallyOwned
)
public function Mutex (
    initiallyOwned : boolean
)

パラメータ

initiallyOwned

呼び出しスレッドミューテックス初期所有権与え場合trueそれ以外場合false

使用例使用例

ローカル 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 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 '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 owns the
    // Mutex.
    private static Mutex mut = new
 Mutex(true);
    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();
        }

        // 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();
    }
}
// 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 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();
}

// 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 owns the
    // Mutex.
    private static Mutex mut = new
 Mutex(true);
    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();
        }

        // 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();
    } //main

    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
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Mutex コンストラクタ (Boolean, String, Boolean, MutexSecurity)

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

Boolean 型の値を使用してMutex クラス新しインスタンス初期化します。この Boolean 型の値は、呼び出し元のスレッドミューテックス初期所有権があるかどうかミューテックスの名前を表す文字列、メソッド返されるときにミューテックス初期所有権呼び出し元のスレッド付与されたかどうかを示す Boolean 変数、および名前付ミューテックス適用するアクセス制御セキュリティ示します

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Sub New ( _
    initiallyOwned As Boolean, _
    name As String, _
    <OutAttribute> ByRef createdNew As
 Boolean, _
    mutexSecurity As MutexSecurity _
)
Dim initiallyOwned As Boolean
Dim name As String
Dim createdNew As Boolean
Dim mutexSecurity As MutexSecurity

Dim instance As New Mutex(initiallyOwned,
 name, createdNew, mutexSecurity)
public Mutex (
    bool initiallyOwned,
    string name,
    out bool createdNew,
    MutexSecurity mutexSecurity
)
public:
Mutex (
    bool initiallyOwned, 
    String^ name, 
    [OutAttribute] bool% createdNew, 
    MutexSecurity^ mutexSecurity
)
public Mutex (
    boolean initiallyOwned, 
    String name, 
    /** @attribute OutAttribute() */ /** @ref */ boolean createdNew, 
    MutexSecurity mutexSecurity
)
public function Mutex (
    initiallyOwned : boolean, 
    name : String, 
    createdNew : boolean, 
    mutexSecurity : MutexSecurity
)

パラメータ

initiallyOwned

この呼び出し結果として前付システム ミューテックス作成される場合に、呼び出しスレッドに名前付システム ミューテックス初期所有権付与する場合trueそれ以外場合false

name

システム ミューテックスの名前。値が null 参照 (Visual Basic では Nothing) の場合、Mutex は無名なります

createdNew

このメソッド返されるときに、呼び出し元のスレッドミューテックス初期所有権付与され場合trueBoolean 値が格納されます。それ以外場合false格納されます。このパラメータ初期化せずに渡されます。

mutexSecurity

前付システム ミューテックス適用するアクセス制御セキュリティを表す MutexSecurity オブジェクト

例外例外
例外種類条件

IOException

Win32 エラー発生しました

UnauthorizedAccessException

アクセス制御セキュリティ使用した前付ミューテックス存在しますが、ユーザーに MutexRights.FullControl がありません。

ApplicationException

前付ミューテックス作成できません。別の型の待機ハンドルに同じ名前が付けられていることが原因として考えられます。

ArgumentException

name260 文字超えてます。

解説解説

namenull 参照 (Visual Basic では Nothing) ではなく initiallyOwnedtrue場合呼び出しスレッドは、呼び出し後に createdNewtrue である場合にのみ名前付ミューテックス所有します。それ以外場合スレッドは WaitOne メソッド呼び出すことによってミューテックス要求できます

このコンストラクタは、名前付システム ミューテックス作成時にミューテックスアクセス制御セキュリティ適用して、他のコードミューテックス制御できないようにするために使用します

このコンストラクタは、名前付システム ミューテックスを表す Mutex オブジェクト初期化します。同じ名前付システム ミューテックスを表す複数Mutex オブジェクト作成できます

前付システム ミューテックス存在しない場合指定したアクセス制御セキュリティで名前付システム ミューテックス作成されます。前付システム ミューテックス存在する場合指定したアクセス制御セキュリティ無視されます。

メモメモ

mutexSecurity現在のユーザーに対して一部アクセス権拒否していたり、アクセス権付与できなかったりした場合でも、呼び出し元は新しく作成した Mutex オブジェクトを完全に制御します。ただし、現在のユーザーコンストラクタまたは OpenExisting メソッド使用して、同じ名前付ミューテックスを表す別の Mutex オブジェクト取得しようとした場合は、Windowsアクセス制御セキュリティ適用されます。

前付ミューテックスアクセス制御セキュリティで既に作成されていて、呼び出し元に MutexRights.FullControlない場合は、例外スローさます。スレッド動作同期するために必要な権限でのみ既存の名前付ミューテックスを開く方法については、OpenExisting メソッドに関するトピック参照してください

namenull 参照 (Visual Basic では Nothing) または空の文字列指定すると、Mutex(Boolean) コンストラクタ呼び出した場合同様にローカル ミューテックス作成されます。この場合createdNew は常に true です。

前付ミューテックスシステム全体有効なため、プロセス境界またがってリソース使用調整するために使用できます

使用例使用例

アクセス制御セキュリティ使用した前付ミューテックスプロセス間の動作デモンストレーションするコード例次に示します。この例では、OpenExisting(String) メソッド オーバーロード使用して、名前付ミューテックス存在するかどうかテストしてます。

ミューテックス存在しない場合初期所有権と、現在のユーザーによるミューテックスの使用拒否しミューテックス対す読み取り変更アクセス許可のみ付与するアクセス制御セキュリティミューテックス作成されます。

2 つコマンド ウィンドウからコンパイルした例を実行すると、2 番目のコピーOpenExisting(String)呼び出しアクセス違反例外をスローます。例外キャッチされると、OpenExisting(String,MutexRights) メソッド オーバーロード使用しアクセス許可読み取り変更必要な権限で、ミューテックス開きます

アクセス許可変更された後、入力解放必要な権限ミューテックス開かれます。3 つ目のコマンド ウィンドウからコンパイル済みの例を実行する場合新しアクセス許可使用して実行されます。

Imports System
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()
    End Sub 
End Class 
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;
            MutexSecurity 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();
    }
}
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();
   }
};

int main()
{
   Example::Main();
}
.NET Framework のセキュリティ.NET Frameworkセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Mutex コンストラクタ (Boolean, String, Boolean)

Boolean 型の値を使用してMutex クラス新しインスタンス初期化します。この Boolean 型の値は、呼び出し元のスレッドミューテックス初期所有権があるかどうかミューテックスの名前を表す文字列、およびメソッド返されるときにミューテックス初期所有権呼び出し元のスレッド付与されたかどうかを示す Boolean 値を示します

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Sub New ( _
    initiallyOwned As Boolean, _
    name As String, _
    <OutAttribute> ByRef createdNew As
 Boolean _
)
Dim initiallyOwned As Boolean
Dim name As String
Dim createdNew As Boolean

Dim instance As New Mutex(initiallyOwned,
 name, createdNew)
public Mutex (
    bool initiallyOwned,
    string name,
    out bool createdNew
)
public:
Mutex (
    bool initiallyOwned, 
    String^ name, 
    [OutAttribute] bool% createdNew
)
public Mutex (
    boolean initiallyOwned, 
    String name, 
    /** @attribute OutAttribute() */ /** @ref */ boolean createdNew
)
public function Mutex (
    initiallyOwned : boolean, 
    name : String, 
    createdNew : boolean
)

パラメータ

initiallyOwned

この呼び出し結果として前付システム ミューテックス作成される場合に、呼び出しスレッドに名前付システム ミューテックス初期所有権付与する場合trueそれ以外場合false

name

Mutex の名前。値が null 参照 (Visual Basic では Nothing) の場合Mutex無名なります

createdNew

このメソッド返されるときに、呼び出し元のスレッドミューテックス初期所有権付与され場合trueBoolean 値が格納されます。それ以外場合false格納されます。このパラメータ初期化せずに渡されます。

例外例外
例外種類条件

UnauthorizedAccessException

アクセス制御セキュリティ使用した前付ミューテックス存在しますが、ユーザーに MutexRights.FullControl がありません。

IOException

Win32 エラー発生しました

ApplicationException

前付ミューテックス作成できません。別の型の待機ハンドルに同じ名前が付けられていることが原因として考えられます。

ArgumentException

name260 文字超えてます。

解説解説

namenull 参照 (Visual Basic では Nothing) ではなく initiallyOwnedtrue場合呼び出しスレッドは、呼び出し後に createdNewtrue である場合にのみ名前付ミューテックス所有します。それ以外場合スレッドは WaitOne メソッド呼び出すことによってミューテックス要求できます

このコンストラクタは、名前付システム ミューテックスを表す Mutex オブジェクト初期化します。同じ名前付システム ミューテックスを表す複数Mutex オブジェクト作成できます

前付ミューテックスアクセス制御セキュリティで既に作成されていて、呼び出し元に MutexRights.FullControl 権限ない場合は、例外スローさます。スレッド動作同期するために必要な権限でのみ既存の名前付ミューテックスを開く方法については、OpenExisting メソッドに関するトピック参照してください

namenull 参照 (Visual Basic では Nothing) または空の文字列指定すると、Mutex(Boolean) コンストラクタ呼び出した場合同様にローカル ミューテックス作成されます。この場合createdNew は常に true です。

前付ミューテックスシステム全体有効なため、プロセス境界またがってリソース使用調整するために使用できます

使用例使用例

前付ミューテックス使用してプロセス間またはスレッド間の通知を行うコード例次に示します。このプログラムは、複数コマンド ウィンドウから実行します。各プロセスで、名前付ミューテックス "MyMutex" を表す Mutex オブジェクト作成されます。前付ミューテックスシステム オブジェクトです。この例では、名前付ミューテックス有効期間が、この名前付ミューテックスを表す Mutex オブジェクト有効期間によって制限されています。前付ミューテックスは、最初プロセスローカル Mutex オブジェクト作成されるときに作成され、この名前付ミューテックスを表す Mutex オブジェクトがすべて解放されたときに破棄されます。初期状態では、名前付ミューテックス最初プロセスによって所有されています。2 番目のプロセスおよび後続プロセスは、それ以前プロセスが名前付ミューテックス解放するまで待機します。

' 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
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 'Main
End Class 'Test
// 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 Test
{
    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.
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.
import System.*;
import System.Threading.*;
import System.Threading.Thread;

public class Test
{
    public static void main(String[]
 args)
    {
        // Set this variable to false if you do not want to request
 
        // initial ownership of the named mutex.
        boolean requestInitialOwnership = true;
        boolean mutexWasCreated = false;

        // 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",
 
            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();
    } //main
} //Test
.NET Framework のセキュリティ.NET Frameworkセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Mutex コンストラクタ (Boolean, String)

呼び出し元のスレッドミューテックス初期所有権があるかどうかを示す Boolean 型の値と、ミューテックスの名前を表す文字列を使用してMutex クラス新しインスタンス初期化します。

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Sub New ( _
    initiallyOwned As Boolean, _
    name As String _
)
Dim initiallyOwned As Boolean
Dim name As String

Dim instance As New Mutex(initiallyOwned,
 name)
public Mutex (
    bool initiallyOwned,
    string name
)
public:
Mutex (
    bool initiallyOwned, 
    String^ name
)
public Mutex (
    boolean initiallyOwned, 
    String name
)
public function Mutex (
    initiallyOwned : boolean, 
    name : String
)

パラメータ

initiallyOwned

この呼び出し結果として前付システム ミューテックス作成される場合に、呼び出しスレッドに名前付システム ミューテックス初期所有権付与する場合trueそれ以外場合false

name

Mutex の名前。値が null 参照 (Visual Basic では Nothing) の場合Mutex無名なります

例外例外
例外種類条件

UnauthorizedAccessException

アクセス制御セキュリティ使用した前付ミューテックス存在しますが、ユーザーに MutexRights.FullControl がありません。

IOException

Win32 エラー発生しました

ApplicationException

前付ミューテックス作成できません。別の型の待機ハンドルに同じ名前が付けられていることが原因として考えられます。

ArgumentException

name260 文字超えてます。

解説解説

namenull 参照 (Visual Basic では Nothing) ではなく initiallyOwnedtrue場合呼び出しスレッドは、この呼び出し結果として前付システム ミューテックス作成され場合にのみミューテックス所有します。前付システム ミューテックス作成されたかどうかを確認するしくみはないため、このコンストラクタ オーバーロード呼び出すときは initiallyOwnedfalse設定することをお勧めます。初期所有権があるかどうか調べ必要がある場合は、Mutex(Boolean,String,Boolean) コンストラクタ使用できます

このコンストラクタは、名前付システム ミューテックスを表す Mutex オブジェクト初期化します。同じ名前付システム ミューテックスを表す複数Mutex オブジェクト作成できます

前付ミューテックスアクセス制御セキュリティで既に作成されていて、呼び出し元に MutexRights.FullControlない場合は、例外スローさます。スレッド動作同期するために必要な権限でのみ既存の名前付ミューテックスを開く方法については、OpenExisting メソッドに関するトピック参照してください

namenull 参照 (Visual Basic では Nothing) または空の文字列指定すると、Mutex(Boolean) コンストラクタ呼び出した場合同様にローカル ミューテックス作成されます。この場合createdNew は常に true です。

前付ミューテックスシステム全体有効なため、プロセス境界またがってリソース使用調整するために使用できます

使用例使用例
' 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 constructor overload shown here cannot tell the calling thread
' whether initial ownership of the named mutex was granted. Therefore
,
' do not request initial ownership unless you are certain that the 
' thread will create the named mutex.

Imports System
Imports System.Threading

Public Class Test

   <MTAThread> _
   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 'Main
End Class 'Test
// 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 constructor overload shown here cannot tell the calling thread
// whether initial ownership of the named mutex was granted. Therefore
,
// do not request initial ownership unless you are certain that the
 
// thread will create the named mutex.


using System;
using System.Threading;

public class Test
{
    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();
    }
}
// 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 constructor overload shown here cannot tell the calling thread
// whether initial ownership of the named mutex was granted. Therefore
,
// do not request initial ownership unless you are certain that the
 
// thread will create the named 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();
}

// 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 constructor overload shown here cannot tell the calling thread
// whether initial ownership of the named mutex was granted. Therefore
,
// do not request initial ownership unless you are certain that the
 
// thread will create the named mutex.

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

public class Test
{
    public static void main(String[]
 args)
    {
        // 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();
    } //main
} //Test
.NET Framework のセキュリティ.NET Frameworkセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Mutex コンストラクタ

Mutex クラス新しインスタンス初期化します。
オーバーロードの一覧オーバーロードの一覧

名前 説明
Mutex () Mutex クラス新しインスタンス既定プロパティ使用して初期化します。

.NET Compact Framework によってサポートされています。

Mutex (Boolean) 呼び出し元のスレッドミューテックス初期所有権があるかどうかを示す Boolean 型の値を使用してMutex クラス新しインスタンス初期化します。

.NET Compact Framework によってサポートされています。

Mutex (Boolean, String) 呼び出し元のスレッドミューテックス初期所有権があるかどうかを示す Boolean 型の値と、ミューテックスの名前を表す文字列を使用してMutex クラス新しインスタンス初期化します。
Mutex (Boolean, String, Boolean) Boolean 型の値を使用してMutex クラス新しインスタンス初期化します。この Boolean 型の値は、呼び出し元のスレッドミューテックス初期所有権があるかどうかミューテックスの名前を表す文字列、およびメソッド返されるときにミューテックス初期所有権呼び出し元のスレッド付与されたかどうかを示す Boolean 値を示します
Mutex (Boolean, String, Boolean, MutexSecurity) Boolean 型の値を使用してMutex クラス新しインスタンス初期化します。この Boolean 型の値は、呼び出し元のスレッドミューテックス初期所有権があるかどうかミューテックスの名前を表す文字列、メソッド返されるときにミューテックス初期所有権呼び出し元のスレッド付与されたかどうかを示す Boolean 変数、および名前付ミューテックス適用するアクセス制御セキュリティ示します
参照参照

関連項目

Mutex クラス
Mutex メンバ
System.Threading 名前空間

その他の技術情報

マネージ スレッド処理
ミューテックス

Mutex プロパティ


Mutex メソッド


パブリック メソッドパブリック メソッド

  名前 説明
パブリック メソッド Close  派生クラスオーバーライドされると、現在の WaitHandle で保持されているすべてのリソース解放します。 ( WaitHandle から継承されます。)
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信使用するプロキシ生成必要な情報をすべて格納しているオブジェクト作成します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 ( Object から継承されます。)
パブリック メソッド GetAccessControl 前付ミューテックスアクセス制御セキュリティを表す MutexSecurity オブジェクト取得します
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 ( Object から継承されます。)
パブリック メソッド GetLifetimeService  対象インスタンス有効期間ポリシー制御する現在の有効期間サービス オブジェクト取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 ( Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象インスタンス有効期間ポリシー制御する有効期間サービス オブジェクト取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド OpenExisting オーバーロードされます既存の名前付ミューテックス開きます
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 ( Object から継承されます。)
パブリック メソッド ReleaseMutex Mutex をいったん解放します。
パブリック メソッド SetAccessControl 前付システム ミューテックスアクセス制御セキュリティ設定します
パブリック メソッド SignalAndWait  オーバーロードされます分割不可能な操作として1 つWaitHandle通知し別の WaitHandle待機します。 ( WaitHandle から継承されます。)
パブリック メソッド ToString  現在の Object を表す String返します。 ( Object から継承されます。)
パブリック メソッド WaitAll  オーバーロードされます指定した配列内のすべての要素シグナル受信するまで待機します。 ( WaitHandle から継承されます。)
パブリック メソッド WaitAny  オーバーロードされます指定した配列内のいずれか要素シグナル受信するまで待機します。 ( WaitHandle から継承されます。)
パブリック メソッド WaitOne  オーバーロードされます派生クラスオーバーライドされると、現在の WaitHandleシグナル受信するまで現在のスレッドブロックします。 ( WaitHandle から継承されます。)
参照参照

関連項目

Mutex クラス
System.Threading 名前空間
WaitHandle
Thread

その他の技術情報

マネージ スレッド処理
ミューテックス
マネージ スレッドとアンマネージ スレッド

Mutex メンバ

同期プリミティブは、プロセス間の同期にも使用できます

Mutex データ型公開されるメンバを以下の表に示します


パブリック コンストラクタパブリック コンストラクタ
パブリック プロパティパブリック プロパティ
パブリック メソッドパブリック メソッド
  名前 説明
パブリック メソッド Close  派生クラスオーバーライドされると、現在の WaitHandle で保持されているすべてのリソース解放します。 (WaitHandle から継承されます。)
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信使用するプロキシ生成必要な情報をすべて格納しているオブジェクト作成します。 (MarshalByRefObject から継承されます。)
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 (Object から継承されます。)
パブリック メソッド GetAccessControl 前付ミューテックスアクセス制御セキュリティを表す MutexSecurity オブジェクト取得します
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 (Object から継承されます。)
パブリック メソッド GetLifetimeService  対象インスタンス有効期間ポリシー制御する現在の有効期間サービス オブジェクト取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 (Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象インスタンス有効期間ポリシー制御する有効期間サービス オブジェクト取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド OpenExisting オーバーロードされます既存の名前付ミューテックス開きます
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 (Object から継承されます。)
パブリック メソッド ReleaseMutex Mutex をいったん解放します。
パブリック メソッド SetAccessControl 前付システム ミューテックスアクセス制御セキュリティ設定します
パブリック メソッド SignalAndWait  オーバーロードされます分割不可能な操作として1 つWaitHandle通知し別の WaitHandle待機します。 (WaitHandle から継承されます。)
パブリック メソッド ToString  現在の Object を表す String返します。 (Object から継承されます。)
パブリック メソッド WaitAll  オーバーロードされます指定した配列内のすべての要素シグナル受信するまで待機します。 (WaitHandle から継承されます。)
パブリック メソッド WaitAny  オーバーロードされます指定した配列内のいずれか要素シグナル受信するまで待機します。 (WaitHandle から継承されます。)
パブリック メソッド WaitOne  オーバーロードされます派生クラスオーバーライドされると、現在の WaitHandleシグナル受信するまで現在のスレッドブロックします。 (WaitHandle から継承されます。)
参照参照

関連項目

Mutex クラス
System.Threading 名前空間
WaitHandle
Thread

その他の技術情報

マネージ スレッド処理
ミューテックス
マネージ スレッドとアンマネージ スレッド

ミューテックス

(mutex から転送)

出典: フリー百科事典『ウィキペディア(Wikipedia)』 (2023/10/20 20:40 UTC 版)

ミューテックス (: mutex) とは、コンピュータプログラミングにおける技術用語。クリティカルセクションアトミック性を確保するための排他制御同期機構の一種である。「mutex」という語は「mutual exclusion」 (相互排他、排他制御) の省略形である。ここでは、狭義の排他制御について述べる。




「ミューテックス」の続きの解説一覧


英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「mutex」の関連用語











mutexのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



mutexのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.
ウィキペディアウィキペディア
All text is available under the terms of the GNU Free Documentation License.
この記事は、ウィキペディアのミューテックス (改訂履歴)の記事を複製、再配布したものにあたり、GNU Free Documentation Licenseというライセンスの下で提供されています。 Weblio辞書に掲載されているウィキペディアの記事も、全てGNU Free Documentation Licenseの元に提供されております。

©2024 GRAS Group, Inc.RSS