This documentation is archived and is not being maintained.
Mutex Constructor (Boolean)
Visual Studio 2010
Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- initiallyOwned
- Type: System::Boolean
true to give the calling thread initial ownership of the mutex; otherwise, false.
The following code example shows how a local Mutex object is used to synchronize access to a protected resource. The thread that creates the Mutex owns it initially.
// 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(); }
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Show: