マネージ C++ には、C# のlock()および VB の SyncLock と同等のものがありますか? もしそうなら、私はそれをどのように使用しますか?
4 に答える
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.
ロック / SyncLock に相当するのは、Monitorクラスを使用することです。
.NET 1-3.5sp では、lock(obj) は次のことを行います。
Monitor.Enter(obj);
try
{
// Do work
}
finally
{
Monitor.Exit(obj);
}
.NET 4 以降では、次のようになります。
bool taken = false;
try
{
Monitor.Enter(obj, ref taken);
// Do work
}
finally
{
if (taken)
{
Monitor.Exit(obj);
}
}
次のようにして、これを C++ に変換できます。
System::Object^ obj = gcnew System::Object();
Monitor::Enter(obj);
try
{
// Do work
}
finally
{
Monitor::Exit(obj);
}
lock
C++にはキーワードに相当するものはありません。代わりにこれを行うことができます:
Monitor::Enter(instanceToLock);
try
{
// Only one thread could execute this code at a time
}
finally
{
Monitor::Exit(instanceToLock);
}
Threading.Monitorを試してください。そしてキャッチ。