Mutex クラス

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

この型のすべてのメンバの一覧については、Mutex メンバ を参照してください。

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

NotInheritable Public Class Mutex
   Inherits WaitHandle
[C#]
public sealed class Mutex : WaitHandle
[C++]
public __gc __sealed class Mutex : public WaitHandle
[JScript]
public class Mutex extends WaitHandle

スレッドセーフ

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

解説

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

ミューテックスの所有権を要求するには、 WaitHandle.WaitOne を使用します。スレッドがミューテックスを所有していると、 Wait の呼び出しを繰り返すときに、スレッドの実行をブロックせずに同じミューテックスを要求できます。ただし、ミューテックスの所有権を解放する場合、このスレッドは 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
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

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

[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 <mscorlib.dll>

using namespace System;
using namespace System::Threading;

const int numIterations = 1;
const int numThreads = 3;

__gc class Test
{
public:
    // Create a new Mutex. The creating thread does not own the
    // Mutex.
    static Mutex* mut = new 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(S"{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(S"{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 = new Thread(
            new ThreadStart(0, Test::MyThreadProc)
            );
        myThread->Name = String::Format(S"Thread {0}", __box(i + 1));
        myThread->Start();
    }

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

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

名前空間: System.Threading

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ, .NET Compact Framework - Windows CE .NET

アセンブリ: Mscorlib (Mscorlib.dll 内)

参照

Mutex メンバ | System.Threading 名前空間 | WaitHandle | Thread | スレッド処理 | Mutex | マネージ スレッドとアンマネージ スレッド