This topic shows how to implement the C# lock keyword in C++. For more information, see
You can also use the lock class in the C++ Support Library. See
Example
В | Copy Code |
---|---|
// CS_lock_in_CPP.cpp // compile with: /clr /c using namespace System::Threading; ref class Lock { Object^ m_pObject; Lock % operator=( Lock const % ); Lock( Lock const % ); public: Lock( Object ^ pObject ) : m_pObject( pObject ) { Monitor::Enter( m_pObject ); } ~Lock() { Monitor::Exit( m_pObject ); } }; ref struct LockHelper { void DoSomething(); }; void LockHelper::DoSomething() { // Note: Reference type with stack allocation semantics to provide // deterministic finalization Lock lock( this ); // LockHelper instance is locked } |