lock クラスlock Class

このクラスは、複数のスレッドからオブジェクトへのアクセスを同期するためのロックの取得を自動化します。This class automates taking a lock for synchronizing access to an object from several threads. 構築されると、ロックを取得し、破棄されるとロックを解放します。When constructed it acquires the lock and when destroyed it releases the lock.

構文Syntax

ref class lock;

解説Remarks

lockは CLR オブジェクトでのみ使用でき、CLR コードでのみ使用できます。lock is available only for CLR objects and can only be used in CLR code.

内部的には、ロック クラスはMonitorアクセスの同期に使用します。Internally, the lock class uses Monitor to synchronize access. 詳細については、参照先の記事を参照してください。For more information, see the referenced article.

メンバーMembers

パブリック コンストラクターPublic constructors

名前Name 説明Description
ロック::ロックlock::lock ロックをlock永遠に取得するのを待機するオブジェクトを、指定した時間だけ、またはまったく行わないオブジェクトを構築します。Constructs a lock object, optionally waiting to acquire the lock forever, for a specified amount of time, or not at all.
lock::~locklock::~lock オブジェクトをlock破棄します。Destructs a lock object.

パブリック メソッドPublic methods

名前Name 説明Description
lock::acquirelock::acquire オブジェクトのロックを取得し、オプションでロックを永遠に取得するのを待機するか、指定した時間だけ、またはまったくロックを取得しない。Acquires a lock on an object, optionally waiting to acquire the lock forever, for a specified amount of time, or not at all.
lock::is_lockedlock::is_locked ロックが保持されているかどうかを示します。Indicates whether a lock is being held.
lock::releaselock::release ロックを解除します。Releases a lock.
lock::try_acquirelock::try_acquire オブジェクトのロックを取得し、指定された時間待機し、例外をスローする代boolわりに取得の成功を報告するためにを返します。Acquires a lock on an object, waiting for a specified amount of time and returning a bool to report the success of acquisition instead of throwing an exception.

公共事業者Public operators

名前Name 説明Description
ロック::オペレータ ブールlock::operator bool 条件式でlock使用する演算子。Operator for using lock in a conditional expression.
lock::operator==lock::operator== 等値演算子。Equality operator.
ロック::演算子!=lock::operator!= 不等式演算子。Inequality operator.

必要条件Requirements

ヘッダー ファイル<msclr\lock.h>Header file <msclr\lock.h>

名前空間msclrNamespace msclr

ロック::ロックlock::lock

ロックをlock永遠に取得するのを待機するオブジェクトを、指定した時間だけ、またはまったく行わないオブジェクトを構築します。Constructs a lock object, optionally waiting to acquire the lock forever, for a specified amount of time, or not at all.

template<class T> lock(
   T ^ _object
);
template<class T> lock(
   T ^ _object,
   int _timeout
);
template<class T> lock(
   T ^ _object,
   System::TimeSpan _timeout
);
template<class T> lock(
   T ^ _object,
   lock_later
);

パラメーターParameters

_object_object
ロックするオブジェクト。The object to be locked.

_timeout_timeout
タイムアウト値 (ミリ秒単位またはTimeSpan.Time out value in milliseconds or as a TimeSpan.

例外Exceptions

タイムアウト前ApplicationExceptionにロック取得が発生しない場合にスローします。Throws ApplicationException if lock acquisition doesn't occur before timeout.

解説Remarks

コンストラクタの最初の 3 つの形式は、指定された_objectタイムアウト期間内 (またはInfinite指定されていない場合) にロックを取得しようとします。The first three forms of the constructor try to acquire a lock on _object within the specified timeout period (or Infinite if none is specified).

コンストラクタの 4 番目の形式では、 のロック_objectは取得されません。The fourth form of the constructor doesn't acquire a lock on _object. lock_later、lock_when列挙型のメンバーです。lock_later is a member of the lock_when enum. この場合、ロックを取得するにはlock::acquireまたはlock::try_acquireを使用します。Use lock::acquire or lock::try_acquire to acquire the lock in this case.

デストラクターが呼び出されると、ロックは自動的に解放されます。The lock will automatically be released when the destructor is called.

_objectはできませんReaderWriterLock_object can't be ReaderWriterLock. コンパイル エラーが発生した場合は、エラーが発生します。If it is, a compiler error will result.

Example

この例では、複数のスレッドでクラスの単一インスタンスを使用します。This example uses a single instance of a class across several threads. クラスは、自身のロックを使用して、内部データへのアクセスが各スレッドに対して一貫していることを確認します。The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. メイン アプリケーション スレッドは、クラスの同じインスタンスのロックを使用して、ワーカー スレッドがまだ存在するかどうか定期的に確認します。The main application thread uses a lock on the same instance of the class to periodically check to see if any worker threads still exist. メイン アプリケーションは、すべてのワーカー スレッドがタスクを完了するまで終了するまで待機します。The main application then waits to exit until all worker threads have completed their tasks.

// msl_lock_lock.cpp
// compile with: /clr
#include <msclr/lock.h>

using namespace System;
using namespace System::Threading;
using namespace msclr;

ref class CounterClass {
private:
   int Counter;

public:
   property int ThreadCount;

   // function called by multiple threads, use lock to keep Counter consistent
   // for each thread
   void UseCounter() {
      try {
         lock l(this); // wait infinitely

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         for (int i = 0; i < 10; i++) {
            Counter++;
            Thread::Sleep(10);
         }

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         Counter = 0;
         // lock is automatically released when it goes out of scope and its destructor is called
      }
      catch (...) {
         Console::WriteLine("Couldn't acquire lock!");
      }

      ThreadCount--;
   }
};

int main() {
   // create a few threads to contend for access to the shared data
   CounterClass^ cc = gcnew CounterClass;
   array<Thread^>^ tarr = gcnew array<Thread^>(5);
   ThreadStart^ startDelegate = gcnew ThreadStart(cc, &CounterClass::UseCounter);
   for (int i = 0; i < tarr->Length; i++) {
      tarr[i] = gcnew Thread(startDelegate);
      cc->ThreadCount++;
      tarr[i]->Start();
   }

   // keep our main thread alive until all worker threads have completed
   lock l(cc, lock_later); // don't lock now, just create the object
   while (true) {
      if (l.try_acquire(50)) { // try to acquire lock, don't throw an exception if can't
         if (0 == cc->ThreadCount) {
            Console::WriteLine("All threads completed.");
            break; // all threads are gone, exit while
         }
         else {
            Console::WriteLine("{0} threads exist, continue waiting...", cc->ThreadCount);
            l.release(); // some threads exist, let them do their work
         }
      }
   }
}
In thread 3, Counter = 0
In thread 3, Counter = 10
In thread 5, Counter = 0
In thread 5, Counter = 10
In thread 7, Counter = 0
In thread 7, Counter = 10
In thread 4, Counter = 0
In thread 4, Counter = 10
In thread 6, Counter = 0
In thread 6, Counter = 10
All threads completed.

ロック::~ロックlock::~lock

オブジェクトをlock破棄します。Destructs a lock object.

~lock();

解説Remarks

デストラクターはlock::releaseを呼び出します。The destructor calls lock::release.

Example

この例では、複数のスレッドでクラスの単一インスタンスを使用します。This example uses a single instance of a class across several threads. クラスは、自身のロックを使用して、内部データへのアクセスが各スレッドに対して一貫していることを確認します。The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. メイン アプリケーション スレッドは、クラスの同じインスタンスのロックを使用して、ワーカー スレッドがまだ存在するかどうか定期的に確認します。The main application thread uses a lock on the same instance of the class to periodically check to see if any worker threads still exist. メイン アプリケーションは、すべてのワーカー スレッドがタスクを完了するまで終了するまで待機します。The main application then waits to exit until all worker threads have completed their tasks.

// msl_lock_dtor.cpp
// compile with: /clr
#include <msclr/lock.h>

using namespace System;
using namespace System::Threading;
using namespace msclr;

ref class CounterClass {
private:
   int Counter;

public:
   property int ThreadCount;

   // function called by multiple threads, use lock to keep Counter consistent
   // for each thread
   void UseCounter() {
      try {
         lock l(this); // wait infinitely

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         for (int i = 0; i < 10; i++) {
            Counter++;
            Thread::Sleep(10);
         }

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         Counter = 0;
         // lock is automatically released when it goes out of scope and its destructor is called
      }
      catch (...) {
         Console::WriteLine("Couldn't acquire lock!");
      }

      ThreadCount--;
   }
};

int main() {
   // create a few threads to contend for access to the shared data
   CounterClass^ cc = gcnew CounterClass;
   array<Thread^>^ tarr = gcnew array<Thread^>(5);
   ThreadStart^ startDelegate = gcnew ThreadStart(cc, &CounterClass::UseCounter);
   for (int i = 0; i < tarr->Length; i++) {
      tarr[i] = gcnew Thread(startDelegate);
      cc->ThreadCount++;
      tarr[i]->Start();
   }

   // keep our main thread alive until all worker threads have completed
   lock l(cc, lock_later); // don't lock now, just create the object
   while (true) {
      if (l.try_acquire(50)) { // try to acquire lock, don't throw an exception if can't
         if (0 == cc->ThreadCount) {
            Console::WriteLine("All threads completed.");
            break; // all threads are gone, exit while
         }
         else {
            Console::WriteLine("{0} threads exist, continue waiting...", cc->ThreadCount);
            l.release(); // some threads exist, let them do their work
         }
      }
   }
}
In thread 3, Counter = 0
In thread 3, Counter = 10
In thread 5, Counter = 0
In thread 5, Counter = 10
In thread 7, Counter = 0
In thread 7, Counter = 10
In thread 4, Counter = 0
In thread 4, Counter = 10
In thread 6, Counter = 0
In thread 6, Counter = 10
All threads completed.

ロック::取得lock::acquire

オブジェクトのロックを取得し、オプションでロックを永遠に取得するのを待機するか、指定した時間だけ、またはまったくロックを取得しない。Acquires a lock on an object, optionally waiting to acquire the lock forever, for a specified amount of time, or not at all.

void acquire();
void acquire(
   int _timeout
);
void acquire(
   System::TimeSpan _timeout
);

パラメーターParameters

_timeout_timeout
タイムアウト値 (ミリ秒単位またはTimeSpan)。Timeout value in milliseconds or as a TimeSpan.

例外Exceptions

タイムアウト前ApplicationExceptionにロック取得が発生しない場合にスローします。Throws ApplicationException if lock acquisition doesn't occur before timeout.

解説Remarks

タイムアウト値が指定されていない場合、デフォルトのタイムアウトはInfiniteです。If a timeout value isn't supplied, the default timeout is Infinite.

ロックがすでに取得されている場合、この関数は何も実行しません。If a lock has already been acquired, this function does nothing.

Example

この例では、複数のスレッドでクラスの単一インスタンスを使用します。This example uses a single instance of a class across several threads. クラスは、自身のロックを使用して、内部データへのアクセスが各スレッドに対して一貫していることを確認します。The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. メイン アプリケーション スレッドは、クラスの同じインスタンスのロックを使用して、ワーカー スレッドがまだ存在するかどうか定期的に確認します。The main application thread uses a lock on the same instance of the class to periodically check to see if any worker threads still exist. メイン アプリケーションは、すべてのワーカー スレッドがタスクを完了するまで終了するまで待機します。The main application then waits to exit until all worker threads have completed their tasks.

// msl_lock_acquire.cpp
// compile with: /clr
#include <msclr/lock.h>

using namespace System;
using namespace System::Threading;
using namespace msclr;

ref class CounterClass {
private:
   int Counter;

public:
   property int ThreadCount;

   // function called by multiple threads, use lock to keep Counter consistent
   // for each thread
   void UseCounter() {
      try {
         lock l(this); // wait infinitely

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         for (int i = 0; i < 10; i++) {
            Counter++;
            Thread::Sleep(10);
         }

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         Counter = 0;
         // lock is automatically released when it goes out of scope and its destructor is called
      }
      catch (...) {
         Console::WriteLine("Couldn't acquire lock!");
      }

      ThreadCount--;
   }
};

int main() {
   // create a few threads to contend for access to the shared data
   CounterClass^ cc = gcnew CounterClass;
   array<Thread^>^ tarr = gcnew array<Thread^>(5);
   ThreadStart^ startDelegate = gcnew ThreadStart(cc, &CounterClass::UseCounter);
   for (int i = 0; i < tarr->Length; i++) {
      tarr[i] = gcnew Thread(startDelegate);
      cc->ThreadCount++;
      tarr[i]->Start();
   }

   // keep our main thread alive until all worker threads have completed
   lock l(cc, lock_later); // don't lock now, just create the object
   while (true) {
      if (l.try_acquire(50)) { // try to acquire lock, don't throw an exception if can't
         if (0 == cc->ThreadCount) {
            Console::WriteLine("All threads completed.");
            break; // all threads are gone, exit while
         }
         else {
            Console::WriteLine("{0} threads exist, continue waiting...", cc->ThreadCount);
            l.release(); // some threads exist, let them do their work
         }
      }
   }
}
In thread 3, Counter = 0
In thread 3, Counter = 10
In thread 5, Counter = 0
In thread 5, Counter = 10
In thread 7, Counter = 0
In thread 7, Counter = 10
In thread 4, Counter = 0
In thread 4, Counter = 10
In thread 6, Counter = 0
In thread 6, Counter = 10
All threads completed.

ロック::is_lockedlock::is_locked

ロックが保持されているかどうかを示します。Indicates whether a lock is being held.

bool is_locked();

戻り値Return value

trueロックが保持されている場合、falseそれ以外の場合。true if a lock is held, false otherwise.

Example

この例では、複数のスレッドでクラスの単一インスタンスを使用します。This example uses a single instance of a class across several threads. クラスは、自身のロックを使用して、内部データへのアクセスが各スレッドに対して一貫していることを確認します。The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. メイン アプリケーション スレッドは、クラスの同じインスタンスのロックを使用して、ワーカー スレッドがまだ存在するかどうか定期的に確認し、すべてのワーカー スレッドがタスクを完了するまで終了するのを待機します。The main application thread uses a lock on the same instance of the class to periodically check to see if any worker threads still exist, and waits to exit until all worker threads have completed their tasks.

// msl_lock_is_locked.cpp
// compile with: /clr
#include <msclr/lock.h>

using namespace System;
using namespace System::Threading;
using namespace msclr;

ref class CounterClass {
private:
   int Counter;

public:
   property int ThreadCount;

   // function called by multiple threads, use lock to keep Counter consistent
   // for each thread
   void UseCounter() {
      try {
         lock l(this); // wait infinitely

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         for (int i = 0; i < 10; i++) {
            Counter++;
            Thread::Sleep(10);
         }

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         Counter = 0;
         // lock is automatically released when it goes out of scope and its destructor is called
      }
      catch (...) {
         Console::WriteLine("Couldn't acquire lock!");
      }

      ThreadCount--;
   }
};

int main() {
   // create a few threads to contend for access to the shared data
   CounterClass^ cc = gcnew CounterClass;
   array<Thread^>^ tarr = gcnew array<Thread^>(5);
   ThreadStart^ startDelegate = gcnew ThreadStart(cc, &CounterClass::UseCounter);
   for (int i = 0; i < tarr->Length; i++) {
      tarr[i] = gcnew Thread(startDelegate);
      cc->ThreadCount++;
      tarr[i]->Start();
   }

   // keep our main thread alive until all worker threads have completed
   lock l(cc, lock_later); // don't lock now, just create the object
   while (true) {
      l.try_acquire(50); // try to acquire lock, don't throw an exception if can't
      if (l.is_locked()) { // check if we got the lock
         if (0 == cc->ThreadCount) {
            Console::WriteLine("All threads completed.");
            break; // all threads are gone, exit while
         }
         else {
            Console::WriteLine("{0} threads exist, continue waiting...", cc->ThreadCount);
            l.release(); // some threads exist, let them do their work
         }
      }
   }
}
In thread 3, Counter = 0
In thread 3, Counter = 10
In thread 5, Counter = 0
In thread 5, Counter = 10
In thread 4, Counter = 0
In thread 4, Counter = 10
In thread 7, Counter = 0
In thread 7, Counter = 10
In thread 6, Counter = 0
In thread 6, Counter = 10
All threads completed.

ロック::オペレータブールlock::operator bool

条件式でlock使用する演算子。Operator for using lock in a conditional expression.

operator bool();

戻り値Return value

trueロックが保持されている場合、falseそれ以外の場合。true if a lock is held, false otherwise.

解説Remarks

この演算子は、整数型_detail_class::_safe_boolに変換できないため、bool実際に変換する方が安全です。This operator actually converts to _detail_class::_safe_bool which is safer than bool because it can't be converted to an integral type.

Example

この例では、複数のスレッドでクラスの単一インスタンスを使用します。This example uses a single instance of a class across several threads. クラスは、自身のロックを使用して、内部データへのアクセスが各スレッドに対して一貫していることを確認します。The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. メイン アプリケーション スレッドは、クラスの同じインスタンスのロックを使用して、ワーカー スレッドがまだ存在するかどうか定期的に確認します。The main application thread uses a lock on the same instance of the class to periodically check to see if any worker threads still exist. メイン アプリケーションは、すべてのワーカー スレッドがタスクを完了するまで終了するまで待機します。The main application waits to exit until all worker threads have completed their tasks.

// msl_lock_op_bool.cpp
// compile with: /clr
#include <msclr/lock.h>

using namespace System;
using namespace System::Threading;
using namespace msclr;

ref class CounterClass {
private:
   int Counter;

public:
   property int ThreadCount;

   // function called by multiple threads, use lock to keep Counter consistent
   // for each thread
   void UseCounter() {
      try {
         lock l(this); // wait infinitely

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         for (int i = 0; i < 10; i++) {
            Counter++;
            Thread::Sleep(10);
         }

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         Counter = 0;
         // lock is automatically released when it goes out of scope and its destructor is called
      }
      catch (...) {
         Console::WriteLine("Couldn't acquire lock!");
      }

      ThreadCount--;
   }
};

int main() {
   // create a few threads to contend for access to the shared data
   CounterClass^ cc = gcnew CounterClass;
   array<Thread^>^ tarr = gcnew array<Thread^>(5);
   ThreadStart^ startDelegate = gcnew ThreadStart(cc, &CounterClass::UseCounter);
   for (int i = 0; i < tarr->Length; i++) {
      tarr[i] = gcnew Thread(startDelegate);
      cc->ThreadCount++;
      tarr[i]->Start();
   }

   // keep our main thread alive until all worker threads have completed
   lock l(cc, lock_later); // don't lock now, just create the object
   while (true) {
      l.try_acquire(50); // try to acquire lock, don't throw an exception if can't
      if (l) { // use bool operator to check for lock
         if (0 == cc->ThreadCount) {
            Console::WriteLine("All threads completed.");
            break; // all threads are gone, exit while
         }
         else {
            Console::WriteLine("{0} threads exist, continue waiting...", cc->ThreadCount);
            l.release(); // some threads exist, let them do their work
         }
      }
   }
}
In thread 3, Counter = 0
In thread 3, Counter = 10
In thread 5, Counter = 0
In thread 5, Counter = 10
In thread 7, Counter = 0
In thread 7, Counter = 10
In thread 4, Counter = 0
In thread 4, Counter = 10
In thread 6, Counter = 0
In thread 6, Counter = 10
All threads completed.

ロック::リリースlock::release

ロックを解除します。Releases a lock.

void release();

解説Remarks

ロックが保持されていない場合は、release何もしません。If no lock is being held, release does nothing.

この関数を明示的に呼び出す必要はありません。You don't have to call this function explicitly. オブジェクトがlockスコープ外に出ると、そのデストラクターがrelease呼び出されます。When a lock object goes out of scope, its destructor calls release.

Example

この例では、複数のスレッドでクラスの単一インスタンスを使用します。This example uses a single instance of a class across several threads. クラスは、自身のロックを使用して、内部データへのアクセスが各スレッドに対して一貫していることを確認します。The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. メイン アプリケーション スレッドは、クラスの同じインスタンスのロックを使用して、ワーカー スレッドがまだ存在するかどうか定期的に確認します。The main application thread uses a lock on the same instance of the class to periodically check to see if any worker threads still exist. メイン アプリケーションは、すべてのワーカー スレッドがタスクを完了するまで終了するまで待機します。The main application then waits to exit until all worker threads have completed their tasks.

// msl_lock_release.cpp
// compile with: /clr
#include <msclr/lock.h>

using namespace System;
using namespace System::Threading;
using namespace msclr;

ref class CounterClass {
private:
   int Counter;

public:
   property int ThreadCount;

   // function called by multiple threads, use lock to keep Counter consistent
   // for each thread
   void UseCounter() {
      try {
         lock l(this); // wait infinitely

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         for (int i = 0; i < 10; i++) {
            Counter++;
            Thread::Sleep(10);
         }

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         Counter = 0;
         // lock is automatically released when it goes out of scope and its destructor is called
      }
      catch (...) {
         Console::WriteLine("Couldn't acquire lock!");
      }

      ThreadCount--;
   }
};

int main() {
   // create a few threads to contend for access to the shared data
   CounterClass^ cc = gcnew CounterClass;
   array<Thread^>^ tarr = gcnew array<Thread^>(5);
   ThreadStart^ startDelegate = gcnew ThreadStart(cc, &CounterClass::UseCounter);
   for (int i = 0; i < tarr->Length; i++) {
      tarr[i] = gcnew Thread(startDelegate);
      cc->ThreadCount++;
      tarr[i]->Start();
   }

   // keep our main thread alive until all worker threads have completed
   lock l(cc, lock_later); // don't lock now, just create the object
   while (true) {
      if (l.try_acquire(50)) { // try to acquire lock, don't throw an exception if can't
         if (0 == cc->ThreadCount) {
            Console::WriteLine("All threads completed.");
            break; // all threads are gone, exit while
         }
         else {
            Console::WriteLine("{0} threads exist, continue waiting...", cc->ThreadCount);
            l.release(); // some threads exist, let them do their work
         }
      }
   }
}
In thread 3, Counter = 0
In thread 3, Counter = 10
In thread 5, Counter = 0
In thread 5, Counter = 10
In thread 7, Counter = 0
In thread 7, Counter = 10
In thread 4, Counter = 0
In thread 4, Counter = 10
In thread 6, Counter = 0
In thread 6, Counter = 10
All threads completed.

ロック::try_acquirelock::try_acquire

オブジェクトのロックを取得し、指定された時間待機し、例外をスローする代boolわりに取得の成功を報告するためにを返します。Acquires a lock on an object, waiting for a specified amount of time and returning a bool to report the success of acquisition instead of throwing an exception.

bool try_acquire(
   int _timeout_ms
);
bool try_acquire(
   System::TimeSpan _timeout
);

パラメーターParameters

_timeout_timeout
タイムアウト値 (ミリ秒単位またはTimeSpan)。Timeout value in milliseconds or as a TimeSpan.

戻り値Return value

trueロックが取得された場合false、それ以外の場合。true if lock was acquired, false otherwise.

解説Remarks

ロックがすでに取得されている場合、この関数は何も実行しません。If a lock has already been acquired, this function does nothing.

Example

この例では、複数のスレッドでクラスの単一インスタンスを使用します。This example uses a single instance of a class across several threads. クラスは、自身のロックを使用して、内部データへのアクセスが各スレッドに対して一貫していることを確認します。The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. メイン アプリケーション スレッドは、クラスの同じインスタンスのロックを使用して、ワーカー スレッドがまだ存在するかどうか定期的に確認します。The main application thread uses a lock on the same instance of the class to periodically check to see if any worker threads still exist. メイン アプリケーションは、すべてのワーカー スレッドがタスクを完了するまで終了するまで待機します。The main application then waits to exit until all worker threads have completed their tasks.

// msl_lock_try_acquire.cpp
// compile with: /clr
#include <msclr/lock.h>

using namespace System;
using namespace System::Threading;
using namespace msclr;

ref class CounterClass {
private:
   int Counter;

public:
   property int ThreadCount;

   // function called by multiple threads, use lock to keep Counter consistent
   // for each thread
   void UseCounter() {
      try {
         lock l(this); // wait infinitely

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         for (int i = 0; i < 10; i++) {
            Counter++;
            Thread::Sleep(10);
         }

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId,
            Counter);

         Counter = 0;
         // lock is automatically released when it goes out of scope and its destructor is called
      }
      catch (...) {
         Console::WriteLine("Couldn't acquire lock!");
      }

      ThreadCount--;
   }
};

int main() {
   // create a few threads to contend for access to the shared data
   CounterClass^ cc = gcnew CounterClass;
   array<Thread^>^ tarr = gcnew array<Thread^>(5);
   ThreadStart^ startDelegate = gcnew ThreadStart(cc, &CounterClass::UseCounter);
   for (int i = 0; i < tarr->Length; i++) {
      tarr[i] = gcnew Thread(startDelegate);
      cc->ThreadCount++;
      tarr[i]->Start();
   }

   // keep our main thread alive until all worker threads have completed
   lock l(cc, lock_later); // don't lock now, just create the object
   while (true) {
      if (l.try_acquire(50)) { // try to acquire lock, don't throw an exception if can't
         if (0 == cc->ThreadCount) {
            Console::WriteLine("All threads completed.");
            break; // all threads are gone, exit while
         }
         else {
            Console::WriteLine("{0} threads exist, continue waiting...", cc->ThreadCount);
            l.release(); // some threads exist, let them do their work
         }
      }
   }
}
In thread 3, Counter = 0
In thread 3, Counter = 10
In thread 5, Counter = 0
In thread 5, Counter = 10
In thread 7, Counter = 0
In thread 7, Counter = 10
In thread 4, Counter = 0
In thread 4, Counter = 10
In thread 6, Counter = 0
In thread 6, Counter = 10
All threads completed.

ロック::演算子==lock::operator==

等値演算子。Equality operator.

template<class T> bool operator==(
   T t
);

パラメーターParameters

Tt
等しいかどうかを比較するオブジェクト。The object to compare for equality.

戻り値Return value

ロックのオブジェクトと同じかどうかをtrue``t返します。 falseReturns true if t is the same as the lock's object, false otherwise.

Example

// msl_lock_op_eq.cpp
// compile with: /clr
#include <msclr/lock.h>

using namespace System;
using namespace System::Threading;
using namespace msclr;

int main () {
   Object^ o1 = gcnew Object;
   lock l1(o1);
   if (l1 == o1) {
      Console::WriteLine("Equal!");
   }
}
Equal!

ロック::演算子!=lock::operator!=

不等式演算子。Inequality operator.

template<class T> bool operator!=(
   T t
);

パラメーターParameters

Tt
不等式を比較するオブジェクト。The object to compare for inequality.

戻り値Return value

ロックのオブジェクトと異なるかどうかをtrue``t返します。 falseReturns true if t differs from the lock's object, false otherwise.

Example

// msl_lock_op_ineq.cpp
// compile with: /clr
#include <msclr/lock.h>

using namespace System;
using namespace System::Threading;
using namespace msclr;

int main () {
   Object^ o1 = gcnew Object;
   Object^ o2 = gcnew Object;
   lock l1(o1);
   if (l1 != o2) {
      Console::WriteLine("Inequal!");
   }
}
Inequal!