views:

424

answers:

3

Does managed C++ have an equivalent to C#'s lock() and VB's SyncLock? If so, how do I use it?

+8  A: 

The equivelent to a lock / SyncLock would be to use the Monitor class.

In .NET 1-3.5sp, lock(obj) does:

Monitor.Enter(obj);
try
{
    // Do work
}
finally
{
    Monitor.Exit(obj);
}

As of .NET 4, it will be:

bool taken = false;
try
{
    Monitor.Enter(obj, ref taken);
    // Do work
}
finally
{
    if (taken)
    {
        Monitor.Exit(obj);
    }
}

You could translate this to C++ by doing:

System::Object^ obj = gcnew System::Object();
Monitor::Enter(obj);
try
{
    // Do work
}
finally
{
    Monitor::Exit(obj);
}
Reed Copsey
A: 

Try Threading.Monitor. And catch.

ima
+2  A: 

There's no equivalent of the lock keyword in C++. You could do this instead:

Monitor::Enter(instanceToLock);
try
{
    // Only one thread could execute this code at a time
}
finally
{
    Monitor::Exit(instanceToLock);
}
Darin Dimitrov