.NET Framework クラス ライブラリ
Mutex クラス

更新 : 2007 年 11 月

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

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

構文

Visual Basic (宣言)
<ComVisibleAttribute(True)> _
<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True,  _
    ExternalThreading := True)> _
Public NotInheritable Class Mutex _
    Inherits WaitHandle
Visual Basic (使用法)
Dim instance As Mutex
C#
[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
    ExternalThreading = true)]
public sealed class Mutex : WaitHandle
Visual C++
[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction::LinkDemand, Synchronization = true, 
    ExternalThreading = true)]
public ref class Mutex sealed : public WaitHandle
J#
/** @attribute ComVisibleAttribute(true) */
/** @attribute HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true) */
public final class Mutex extends WaitHandle
JScript
public final class Mutex extends WaitHandle
解説

メモ :

この型またはメンバに適用される HostProtectionAttribute 属性の Resources プロパティの値は、Synchronization | ExternalThreading です。HostProtectionAttribute は、デスクトップ アプリケーション (通常、アイコンのダブルクリック、コマンドの入力、またはブラウザへの URL の入力により起動されます) には影響しません。詳細については、HostProtectionAttribute クラスのトピックまたは「SQL Server プログラミングとホスト保護属性」を参照してください。

複数のスレッドが共有リソースに同時にアクセスする場合、システムには、リソースを使用するのは一度に 1 つのスレッドだけということを保証する同期機構が必要です。Mutex は、共有リソースへの排他アクセス権を 1 つのスレッドにだけ付与する同期プリミティブです。あるスレッドがミューテックスを取得すると、ミューテックスを取得しようとしている 2 つ目のスレッドは最初のスレッドがミューテックスを解放するまで中断されます。

ミューテックスの所有権を要求するには、WaitHandle..::.WaitOne メソッドを使用します。スレッドがミューテックスを所有していると、WaitOne の呼び出しを繰り返すときに、スレッドの実行をブロックせずに同じミューテックスを要求できます。ただし、ミューテックスの所有権を解放する場合、このスレッドは ReleaseMutex メソッドを同じ回数呼び出す必要があります。Mutex クラスはスレッド ID を適用するため、ミューテックスを解放できるのはそのミューテックスを取得したスレッドだけです。これに対して、Semaphore クラスはスレッド ID を適用しません。

ミューテックスを所有しているスレッドが終了した場合は、ミューテックスが放棄されたと言います。ミューテックスはシグナル状態になり、待機していた次のスレッドが所有権を取得します。.NET Framework Version 2.0 以降では、放棄されたミューテックスを取得する次のスレッドで AbandonedMutexException 例外がスローされるようになりました。.NET Framework Version 2.0 より前のバージョンでは、例外はスローされませんでした。

注意 :

放棄されたミューテックスは、多くの場合、コードに深刻なエラーが存在することを意味します。スレッドがミューテックスを解放せずに終了すると、ミューテックスによって保護されるデータ構造の状態に不整合が生じることがあります。ミューテックスの所有権を要求する次のスレッドが、データ構造の整合性を検証できる場合、この例外を処理して続行できます。

システム全体のミューテックスでは、放棄されたミューテックスは、アプリケーションが (たとえば Windows タスク マネージャを使って) 突然終了されたことを意味する場合があります。

ミューテックスには、名前のないローカル ミューテックスと、名前付きシステム ミューテックスの 2 種類があります。ローカル ミューテックスはプロセス内のみに存在します。これは、ミューテックスを表す Mutex オブジェクトへの参照を持つプロセス内のすべてのスレッドで使用できます。名前のない各 Mutex オブジェクトは個別のローカル ミューテックスを表します。

名前付きシステム ミューテックスはオペレーティング システム全体から参照でき、プロセスの動作を同期するために使用できます。名前付きシステム ミューテックスを表す Mutex オブジェクトを作成するには、名前を指定できるコンストラクタを使用します。オペレーティング システム オブジェクトを同時に作成することもできます。または、Mutex オブジェクトの作成前から存在する場合もあります。同じ名前付きシステム ミューテックスを表す複数の Mutex オブジェクトを作成できます。また、OpenExisting メソッドを使用すると、既存の名前付きシステム ミューテックスを開くことができます。

メモ :

ターミナル サービスを実行中のサーバーでは、名前付きシステム ミューテックスには 2 つのレベルの参照範囲があります。名前の先頭のプレフィックスが "Global\" の場合、そのミューテックスはすべてのターミナル サーバー セッションで参照できます。名前の先頭のプレフィックスが "Local\" の場合、そのミューテックスは作成元のターミナル サーバー セッションでのみ参照できます。その場合には、同じサーバー上の他のターミナル サーバー セッションのそれぞれで、同じ名前を持つ別のミューテックスが存在できます。名前付きミューテックスを作成するときにプレフィックスを指定しなかった場合、プレフィックスは "Local\" になります。同じターミナル サーバー セッション内の 2 つのミューテックスで、名前のプレフィックスのみが異なる場合、それらは別個のミューテックスであり、そのターミナル サーバー セッションのすべてのプロセスからどちらも参照できます。つまり、"Global\" と "Local\" というプレフィックスが表すのは、ターミナル サーバー セッションに対する相対的なミューテックス名のスコープです。プロセスに対する相対的なスコープではありません。


ローカル Mutex オブジェクトを使用して、保護されたリソースへのアクセスを同期する方法を次の例に示します。

Visual Basic
' 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
C#
// 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();
    }
}
Visual C++
// 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.
}

J#
// This example shows how a Mutex is used to synchronize access
// to a protected resource. Unlike Monitor, Mutex can be used with
// WaitHandle.WaitAll and WaitAny, and can be passed across
// AppDomain boundaries.

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

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

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

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

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

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

        // Release the Mutex.
        mut.ReleaseMutex();
    } //UseResource
} //Test
継承階層

System..::.Object
  System..::.MarshalByRefObject
    System.Threading..::.WaitHandle
      System.Threading..::.Mutex
スレッド セーフ

この型は、スレッド セーフです。

プラットフォーム

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

.NET Framework および .NET Compact Framework では、各プラットフォームのすべてのバージョンはサポートしていません。サポートされているバージョンについては、「.NET Framework システム要件」を参照してください。

バージョン情報

.NET Framework

サポート対象 : 3.5、3.0、2.0、1.1、1.0

.NET Compact Framework

サポート対象 : 3.5、2.0、1.0

XNA Framework

サポート対象 : 2.0、1.0
参照

参照

その他の技術情報

タグ :


Page view tracker