Assembly : mscorlib (dans mscorlib.dll)
Syntaxe<ComVisibleAttribute(True)> _ Public NotInheritable Class Mutex Inherits WaitHandle
Dim instance As Mutex
[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
Notes Remarque |
|---|
| L'attribut HostProtectionAttribute appliqué à cette classe a la valeur de propriété Resources suivante : Synchronization | ExternalThreading. HostProtectionAttribute n'affecte pas les applications bureautiques (qui sont généralement démarrées en double-cliquant sur une icône, en tapant une commande ou en entrant une URL dans un navigateur). Pour plus d'informations, consultez la classe HostProtectionAttribute ou Attributs de programmation et de protection des hôtes SQL Server. |
Lorsque deux ou plusieurs threads doivent accéder à une ressource partagée en même temps, le système a besoin d'un mécanisme de synchronisation pour garantir qu'un seul thread à la fois utilise cette ressource. Mutex est une primitive de synchronisation qui accorde à un seul thread un accès exclusif à la ressource partagée. Si un thread acquiert un mutex, l'autre thread qui veut acquérir ce mutex est interrompu jusqu'à ce que le premier thread libère le mutex.
Vous pouvez utiliser la méthode WaitHandle.WaitOne pour demander la propriété d'un mutex. Le thread qui possède un mutex peut demander ce mutex dans des appels répétés à WaitOne sans bloquer son exécution. Il doit cependant appeler la méthode ReleaseMutex le même nombre de fois pour abandonner la propriété du mutex. La classe Mutex applique l'identité de thread ; par conséquent un mutex peut être libéré uniquement par le thread qui l'a acquis. Par contraste, la classe Semaphore n'applique pas l'identité de thread.
Si un thread se termine alors qu'il possède un mutex, ce dernier est décrit comme étant abandonné. L'état du mutex est défini à la valeur signalé et le thread en attente suivant obtient la propriété. Si un mutex n'a pas de propriétaire, son état est signalé. Depuis la version 2.0 du .NET Framework, une AbandonedMutexException est levée dans le thread suivant qui acquiert le mutex. Avant la version 2.0 du .NET Framework, aucune exception n'était levée.
Attention |
|---|
| Un mutex abandonné indique une erreur de code grave. Lorsqu'un thread s'arrête sans libérer le mutex, les structures de données protégées par le mutex peuvent ne pas être dans un état cohérent. Le thread suivant qui demande la propriété du mutex peut gérer cette exception et continuer, si l'intégrité des structures de données peut être vérifiée. |
Les mutex sont de deux types : local et système nommé. Si vous créez un objet Mutex à l'aide d'un constructeur qui accepte un nom, il est associé à un objet système d'exploitation portant le même nom. Les mutex de système nommés sont visibles dans tout le système d'exploitation ; ils permettent de synchroniser les activités de processus. Vous pouvez créer plusieurs objets Mutex qui représentent le même mutex système nommé et vous pouvez utiliser la méthode OpenExisting pour ouvrir un mutex système nommé existant.
Un mutex local existe uniquement dans votre processus. Il peut être utilisé par tout thread de votre processus qui a une référence à l'objet Mutex local. Tous les objets Mutex sont des mutex locaux séparés.
Exemple' 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
Plates-formesWindows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile pour Pocket PC, Windows Mobile pour Smartphone, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition
Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.
Informations de version
Remarque
Attention
Outils (masquer)
S'enregistrer
Liste des Membres
Qui est en ligne?
FAQ