This documentation is archived and is not being maintained.
Interlocked::Exchange Method (Int32%, Int32)
Visual Studio 2010
Sets a 32-bit signed integer to a specified value and returns the original value, as an atomic operation.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- location1
- Type: System::Int32%
The variable to set to the specified value.
- value
- Type: System::Int32
The value to which the location1 parameter is set.
| Exception | Condition |
|---|---|
| ArgumentNullException | The address of location1 is a null pointer. |
The following code example shows a thread-safe resource locking mechanism.
using namespace System; using namespace System::Threading; const int numThreads = 10; const int numThreadIterations = 5; ref class MyInterlockedExchangeExampleClass { public: static void MyThreadProc() { for ( int i = 0; i < numThreadIterations; i++ ) { UseResource(); //Wait 1 second before next attempt. Thread::Sleep( 1000 ); } } private: //A simple method that denies reentrancy. static bool UseResource() { //0 indicates that the method is not in use. if ( 0 == Interlocked::Exchange( usingResource, 1 ) ) { Console::WriteLine( " {0} acquired the lock", Thread::CurrentThread->Name ); //Code to access a resource that is not thread safe would go here. //Simulate some work Thread::Sleep( 500 ); Console::WriteLine( " {0} exiting lock", Thread::CurrentThread->Name ); //Release the lock Interlocked::Exchange( usingResource, 0 ); return true; } else { Console::WriteLine( " {0} was denied the lock", Thread::CurrentThread->Name ); return false; } } //0 for false, 1 for true. static int usingResource; }; int main() { Thread^ myThread; Random^ rnd = gcnew Random; for ( int i = 0; i < numThreads; i++ ) { myThread = gcnew Thread( gcnew ThreadStart( MyInterlockedExchangeExampleClass::MyThreadProc ) ); myThread->Name = String::Format( "Thread {0}", i + 1 ); //Wait a random amount of time before starting next thread. Thread::Sleep( rnd->Next( 0, 1000 ) ); myThread->Start(); } }
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: