Versión imprimible       Enviar     
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Esta página es específica de
Microsoft Visual Studio 2005/.NET Framework 2.0

Hay además otras versiones disponibles para:
Mutex (Clase)
Primitiva de sincronización que puede utilizarse también para la sincronización entre procesos.

Espacio de nombres: System.Threading
Ensamblado: mscorlib (en mscorlib.dll)

Visual Basic (Declaración)
<ComVisibleAttribute(True)> _
Public NotInheritable Class Mutex
    Inherits WaitHandle
Visual Basic (Uso)
Dim instance As Mutex
C#
[ComVisibleAttribute(true)] 
public sealed class Mutex : WaitHandle
C++
[ComVisibleAttribute(true)] 
public ref class Mutex sealed : public WaitHandle
J#
/** @attribute ComVisibleAttribute(true) */ 
public final class Mutex extends WaitHandle
JScript
ComVisibleAttribute(true) 
public final class Mutex extends WaitHandle
XAML
No aplicable.
NotaNota:

El atributo HostProtectionAttribute aplicado a esta clase tiene el valor de propiedad Resources siguiente: Synchronization | ExternalThreading. El atributo HostProtectionAttribute no afecta a las aplicaciones de escritorio (que normalmente se inician haciendo doble clic en un icono, escribiendo un comando o introduciendo una dirección URL en el explorador). Para obtener más información, vea la clase HostProtectionAttribute o Programación de SQL Server y atributos de protección del host.

Cuando dos o más subprocesos tienen que obtener acceso a un recurso compartido al mismo tiempo, el sistema necesita un mecanismo de sincronización para garantizar que sólo uno de los subprocesos utilice el recurso en ese momento. Mutex es un primitivo de sincronización que otorga acceso exclusivo al recurso compartido a un solo subproceso. Cuando un subproceso adquiere una exclusión mutua (mutex), el siguiente subproceso que intenta adquirir dicha exclusión mutua se suspende hasta que el primer subproceso libera la exclusión mutua.

Para solicitar la propiedad de una exclusión mutua puede utilizar el método WaitHandle.WaitOne. El subproceso que posee una exclusión mutua puede solicitar la misma exclusión mutua en llamadas repetidas a WaitOne sin bloquear su ejecución. Sin embargo, el subproceso debe llamar al método ReleaseMutex el mismo número de veces para liberar la propiedad de la exclusión mutua. La clase Mutex exige la identidad del subproceso, por lo que sólo podrá liberar la exclusión mutua el subproceso que la adquirió. Por el contrario, la clase Semaphore no exige la identidad del subproceso.

Si un subproceso finaliza mientras posee una exclusión mutua, se dice que la exclusión mutua está abandonada. El estado de la exclusión mutua se establece en señalado y el siguiente subproceso en espera obtiene la propiedad de la exclusión. Si no hay ningún propietario de la exclusión mutua, el estado de la exclusión mutua está señalado. A partir de la versión 2.0 de .NET Framework, se produce una excepción AbandonedMutexException en el siguiente subproceso que adquiere la exclusión mutua. En las versiones de .NET Framework anteriores a la 2.0, no se producía ninguna excepción.

Nota de precauciónPrecaución:

Una exclusión mutua abandonada indica un error grave en el código. Cuando un subproceso sale sin liberar la exclusión mutua, el estado de las estructuras de datos a las que protege la exclusión mutua podría ser inconstante. El siguiente subproceso que solicita la propiedad de la exclusión mutua puede controlar esta excepción y continuar si se puede comprobar la integridad de las estructuras de datos.

Las exclusiones mutuas son de dos tipos: exclusiones mutuas locales y exclusiones mutuas del sistema con nombre. Si crea un objeto Mutex con un constructor que acepta un nombre, se asocia a un objeto del sistema operativo con dicho nombre. Las exclusiones mutuas del sistema con nombre son visibles en todo el sistema operativo y se pueden utilizar para sincronizar las actividades de los procesos. Puede crear varios objetos Mutex que representen la misma exclusión mutua del sistema con nombre y puede utilizar el método OpenExisting para abrir una exclusión mutua del sistema con nombre ya existente.

Una exclusión mutua local sólo existe dentro del proceso del usuario. Puede utilizar la exclusión cualquier subproceso del proceso del usuario que tenga una referencia al objeto Mutex local. Cada objeto Mutex es una exclusión mutua local independiente.

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

Este tipo es seguro para la ejecución de subprocesos.

Windows 98, Windows 2000 Service Pack 4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter

Microsoft .NET Framework 3.0 es compatible con Windows Vista, Microsoft Windows XP SP2 y Windows Server 2003 SP1.

.NET Framework

Compatible con: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 2.0, 1.0

XNA Framework

Compatible con: 1.0
© 2009 Microsoft Corporation. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker