Does managed C++ have an equivalent to C#'s lock() and VB's SyncLock? If so, how do I use it?
Asked
Active
Viewed 1.7k times
4 Answers
68
C++/CLI does have a lock class. All you need to do is declare a lock variable using stack-based semantics, and it will safely exit the monitor when its destructor is called, e.g.:
#include <msclr\lock.h>
{
msclr::lock l(m_lock);
// Do work
} //destructor of lock is called (exits monitor).
m_lock
declaration depends on whether you are synchronising access to an instance or static member.
To protect instance members, use this:
Object^ m_lock = gcnew Object(); // Each class instance has a private lock -
// protects instance members.
To protect static members, use this:
static Object^ m_lock = gcnew Object(); // Type has a private lock -
// protects static members.

Sereger
- 1,083
- 1
- 9
- 11
-
Removed 'dangerous stuff' with 'do work' to not distruct people. Thanks for your comments. – Sereger Sep 26 '11 at 13:40
-
I'm not familiar with C++, how do you declare 'x' ? Thanks – Bastiflew Jun 28 '13 at 12:21
-
Rules for 'x' declaration are the same as in C# as described here: http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx. In summary the guideline is: - define it as a private object, if you want to protect an instance variable; - define it as a private static object variable, if you want to protect a static variable (or if the critical section occurs in a static method in the given class). Thanks for your question - I will enhance the answer. – Sereger Jun 29 '13 at 17:41
22
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
- 554,122
- 78
- 1,158
- 1,373
-
9I'd consider http://stackoverflow.com/questions/1369459/cs-lock-in-managed-c/7527111#7527111 superior in that it is both more in C++ nature (RAII) as well as closer to the C# lock keyword – sehe Sep 26 '11 at 08:56
2
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
- 1,023,142
- 271
- 3,287
- 2,928