C#'s lock() in Managed C++

冷暖自知 提交于 2019-11-29 05:48:56

问题


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


回答1:


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);
}



回答2:


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.



回答3:


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);
}



回答4:


Try Threading.Monitor. And catch.



来源:https://stackoverflow.com/questions/1369459/cs-lock-in-managed-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!