构造 lock 对象,可以选择不等待获取锁之前,在指定时间或。
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
);
参数
_object
要锁定的对象。_timeout
超时值以毫秒或作为 TimeSpan。
异常
,如果锁获取不在超时之前,会引发 ApplicationException 。
备注
构造函数的前三个窗体尝试获取对 _object 的锁在指定的超时时间 (或 Infinite 中,如果未指定)。
构造函数的第四个窗体将不会得到 _object的锁定。lock_later 是 lock_when Enum的成员。使用 lock::acquire 或 lock::try_acquire 在获取锁。
锁定,则调用析构函数,将自动释放。
_object 不能为 ReaderWriterLock。如果是,编译器会出现错误。
示例
此示例使用类的一个实例在多个线程中。类使用在自身的锁确保对其内部数据的访问为每个线程都是一致的。主应用程序线程使用类的同一个实例的锁定期检查任何辅助线程是否仍然存在,并会退出,直到所有辅助线程完成他们的任务。
// 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
}
}
}
}
要求
头文件 <msclr \ lock.h>
命名空间 msclr