lock (Clase)lock Class
Esta clase automatiza la toma de un bloqueo para sincronizar el acceso a un objeto desde varios subprocesos.This class automates taking a lock for synchronizing access to an object from several threads. Cuando se construye, adquiere el bloqueo y, cuando se destruye, libera el bloqueo.When constructed it acquires the lock and when destroyed it releases the lock.
SintaxisSyntax
ref class lock;
ObservacionesRemarks
lock
solo está disponible para objetos CLR y solo se puede usar en código CLR.lock
is available only for CLR objects and can only be used in CLR code.
Internamente, la clase Lock utiliza Monitor para sincronizar el acceso.Internally, the lock class uses Monitor to synchronize access. Para obtener más información, consulte el artículo al que se hace referencia.For more information, see the referenced article.
MiembrosMembers
Constructores públicosPublic constructors
NombreName | DescripciónDescription |
---|---|
Lock:: Locklock::lock | Construye un lock objeto, de manera opcional, en espera para adquirir el bloqueo de forma indefinida, durante un período de tiempo especificado o no en absoluto.Constructs a lock object, optionally waiting to acquire the lock forever, for a specified amount of time, or not at all. |
lock::~locklock::~lock | Destruye un lock objeto.Destructs a lock object. |
Métodos públicosPublic methods
NombreName | DescripciónDescription |
---|---|
lock::acquirelock::acquire | Adquiere un bloqueo en un objeto, de manera opcional, en espera para adquirir el bloqueo de forma indefinida, durante un período de tiempo especificado o no en absoluto.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 | Indica si se mantiene un bloqueo.Indicates whether a lock is being held. |
lock::releaselock::release | Libera un bloqueo.Releases a lock. |
lock::try_acquirelock::try_acquire | Adquiere un bloqueo en un objeto, a la espera de una cantidad de tiempo especificada y devuelve un bool para informar del éxito de la adquisición en lugar de producir una excepción.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. |
Operadores públicosPublic operators
NombreName | DescripciónDescription |
---|---|
Lock:: Operator boollock::operator bool | Operador para usar lock en una expresión condicional.Operator for using lock in a conditional expression. |
lock::operator==lock::operator== | Operador de igualdad.Equality operator. |
Lock:: Operator! =lock::operator!= | Operador de desigualdad.Inequality operator. |
RequisitosRequirements
Archivo de encabezado <msclr\lock.h>Header file <msclr\lock.h>
Espacio de nombres msclrNamespace msclr
Lock:: Locklock::lock
Construye un lock
objeto, de manera opcional, en espera para adquirir el bloqueo de forma indefinida, durante un período de tiempo especificado o no en absoluto.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
);
ParámetrosParameters
_object_object
Objeto que se va a bloquear.The object to be locked.
_timeout_timeout
Valor de tiempo de espera en milisegundos o como TimeSpan .Time out value in milliseconds or as a TimeSpan.
ExcepcionesExceptions
Se produce ApplicationException si la adquisición de bloqueos no se produce antes del tiempo de espera.Throws ApplicationException if lock acquisition doesn't occur before timeout.
ObservacionesRemarks
Las tres primeras formas del constructor intentan adquirir un bloqueo en _object
el período de tiempo de espera especificado (o Infinite si no se especifica ninguno).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).
El cuarto formulario del constructor no adquiere un bloqueo en _object
.The fourth form of the constructor doesn't acquire a lock on _object
. lock_later
es un miembro de la enumeración lock_when.lock_later
is a member of the lock_when enum. Use Lock:: acquire o lock:: try_acquire para adquirir el bloqueo en este caso.Use lock::acquire or lock::try_acquire to acquire the lock in this case.
El bloqueo se liberará automáticamente cuando se llame al destructor.The lock will automatically be released when the destructor is called.
_object
no puede ser ReaderWriterLock ._object
can't be ReaderWriterLock. Si es así, se producirá un error del compilador.If it is, a compiler error will result.
EjemploExample
En este ejemplo se usa una sola instancia de una clase en varios subprocesos.This example uses a single instance of a class across several threads. La clase utiliza un bloqueo para asegurarse de que los accesos a sus datos internos son coherentes para cada subproceso.The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. El subproceso de aplicación principal utiliza un bloqueo en la misma instancia de la clase para comprobar periódicamente si hay algún subproceso de trabajo.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. A continuación, la aplicación principal espera a salir hasta que todos los subprocesos de trabajo hayan completado sus tareas.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:: ~ Locklock::~lock
Destruye un lock
objeto.Destructs a lock
object.
~lock();
ObservacionesRemarks
El destructor llama a Lock:: Release.The destructor calls lock::release.
EjemploExample
En este ejemplo se usa una sola instancia de una clase en varios subprocesos.This example uses a single instance of a class across several threads. La clase utiliza un bloqueo para asegurarse de que los accesos a sus datos internos son coherentes para cada subproceso.The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. El subproceso de aplicación principal utiliza un bloqueo en la misma instancia de la clase para comprobar periódicamente si hay algún subproceso de trabajo.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. A continuación, la aplicación principal espera a salir hasta que todos los subprocesos de trabajo hayan completado sus tareas.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:: acquirelock::acquire
Adquiere un bloqueo en un objeto, de manera opcional, en espera para adquirir el bloqueo de forma indefinida, durante un período de tiempo especificado o no en absoluto.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
);
ParámetrosParameters
_timeout_timeout
Valor de tiempo de espera en milisegundos o como TimeSpan .Timeout value in milliseconds or as a TimeSpan.
ExcepcionesExceptions
Se produce ApplicationException si la adquisición de bloqueos no se produce antes del tiempo de espera.Throws ApplicationException if lock acquisition doesn't occur before timeout.
ObservacionesRemarks
Si no se proporciona un valor de tiempo de espera, el tiempo de espera predeterminado es Infinite .If a timeout value isn't supplied, the default timeout is Infinite.
Si ya se ha adquirido un bloqueo, esta función no hace nada.If a lock has already been acquired, this function does nothing.
EjemploExample
En este ejemplo se usa una sola instancia de una clase en varios subprocesos.This example uses a single instance of a class across several threads. La clase utiliza un bloqueo para asegurarse de que los accesos a sus datos internos son coherentes para cada subproceso.The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. El subproceso de aplicación principal utiliza un bloqueo en la misma instancia de la clase para comprobar periódicamente si hay algún subproceso de trabajo.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. A continuación, la aplicación principal espera a salir hasta que todos los subprocesos de trabajo hayan completado sus tareas.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.
Lock:: is_lockedlock::is_locked
Indica si se mantiene un bloqueo.Indicates whether a lock is being held.
bool is_locked();
Valor devueltoReturn value
true
es si se mantiene un bloqueo, de false
lo contrario, es.true
if a lock is held, false
otherwise.
EjemploExample
En este ejemplo se usa una sola instancia de una clase en varios subprocesos.This example uses a single instance of a class across several threads. La clase utiliza un bloqueo para asegurarse de que los accesos a sus datos internos son coherentes para cada subproceso.The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. El subproceso de aplicación principal utiliza un bloqueo en la misma instancia de la clase para comprobar periódicamente si hay algún subproceso de trabajo y espera a salir hasta que todos los subprocesos de trabajo hayan completado sus tareas.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 boollock::operator bool
Operador para usar lock
en una expresión condicional.Operator for using lock
in a conditional expression.
operator bool();
Valor devueltoReturn value
true
es si se mantiene un bloqueo, de false
lo contrario, es.true
if a lock is held, false
otherwise.
ObservacionesRemarks
Este operador convierte realmente en _detail_class::_safe_bool
el que es más seguro que bool
porque no se puede convertir en un tipo entero.This operator actually converts to _detail_class::_safe_bool
which is safer than bool
because it can't be converted to an integral type.
EjemploExample
En este ejemplo se usa una sola instancia de una clase en varios subprocesos.This example uses a single instance of a class across several threads. La clase utiliza un bloqueo para asegurarse de que los accesos a sus datos internos son coherentes para cada subproceso.The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. El subproceso de aplicación principal utiliza un bloqueo en la misma instancia de la clase para comprobar periódicamente si hay algún subproceso de trabajo.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. La aplicación principal espera a salir hasta que todos los subprocesos de trabajo hayan completado sus tareas.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:: Releaselock::release
Libera un bloqueo.Releases a lock.
void release();
ObservacionesRemarks
Si no se mantiene ningún bloqueo, release
no hace nada.If no lock is being held, release
does nothing.
No es necesario llamar a esta función explícitamente.You don't have to call this function explicitly. Cuando un lock
objeto sale del ámbito, el destructor llama a release
.When a lock
object goes out of scope, its destructor calls release
.
EjemploExample
En este ejemplo se usa una sola instancia de una clase en varios subprocesos.This example uses a single instance of a class across several threads. La clase utiliza un bloqueo para asegurarse de que los accesos a sus datos internos son coherentes para cada subproceso.The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. El subproceso de aplicación principal utiliza un bloqueo en la misma instancia de la clase para comprobar periódicamente si hay algún subproceso de trabajo.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. A continuación, la aplicación principal espera a salir hasta que todos los subprocesos de trabajo hayan completado sus tareas.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.
Lock:: try_acquirelock::try_acquire
Adquiere un bloqueo en un objeto, a la espera de una cantidad de tiempo especificada y devuelve un bool
para informar del éxito de la adquisición en lugar de producir una excepción.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
);
ParámetrosParameters
_timeout_timeout
Valor de tiempo de espera en milisegundos o como TimeSpan .Timeout value in milliseconds or as a TimeSpan.
Valor devueltoReturn value
true
es si se ha adquirido el bloqueo, de false
lo contrario, es.true
if lock was acquired, false
otherwise.
ObservacionesRemarks
Si ya se ha adquirido un bloqueo, esta función no hace nada.If a lock has already been acquired, this function does nothing.
EjemploExample
En este ejemplo se usa una sola instancia de una clase en varios subprocesos.This example uses a single instance of a class across several threads. La clase utiliza un bloqueo para asegurarse de que los accesos a sus datos internos son coherentes para cada subproceso.The class uses a lock on itself to make sure that accesses to its internal data are consistent for each thread. El subproceso de aplicación principal utiliza un bloqueo en la misma instancia de la clase para comprobar periódicamente si hay algún subproceso de trabajo.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. A continuación, la aplicación principal espera a salir hasta que todos los subprocesos de trabajo hayan completado sus tareas.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 = =lock::operator==
Operador de igualdad.Equality operator.
template<class T> bool operator==(
T t
);
ParámetrosParameters
tt
El objeto cuya igualdad se va a comparar.The object to compare for equality.
Valor devueltoReturn value
Devuelve true
si t
es igual que el objeto del bloqueo; de false
lo contrario,.Returns true
if t
is the same as the lock's object, false
otherwise.
EjemploExample
// 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! =lock::operator!=
Operador de desigualdad.Inequality operator.
template<class T> bool operator!=(
T t
);
ParámetrosParameters
tt
Objeto cuya desigualdad se va a comparar.The object to compare for inequality.
Valor devueltoReturn value
Devuelve true
si t
difiere del objeto del bloqueo; de false
lo contrario,.Returns true
if t
differs from the lock's object, false
otherwise.
EjemploExample
// 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!