elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: AIO elhacker.NET 2021 Compilación herramientas análisis y desinfección malware


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  [SOLUCIONADO] Variables "synchronized" en C++/CLI (y en C# quizá también)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [SOLUCIONADO] Variables "synchronized" en C++/CLI (y en C# quizá también)  (Leído 1,501 veces)
SARGE553413

Desconectado Desconectado

Mensajes: 176


Ver Perfil
[SOLUCIONADO] Variables "synchronized" en C++/CLI (y en C# quizá también)
« en: 5 Agosto 2014, 18:48 pm »

Hace poco estuve googleando en busca de alguna keyword similar al "synchronized" de java pero para variables, y pregunté en algún foro (no recuerdo si en este también).
El caso es que en principio parecía que no, pero encontré una manera un tanto farragosa de hacer algo similar, la aporto y de paso pido correcciones si no es correcto algo de lo que digo:

Citar
Lo hago mediante propertys, simplemente declaro un objeto extra en mi clase (de tipo Object por ej., llamado 'lock'), y luego declaro la variable que quiero "synchronized" como si fuera property, y defino sus métodos get y set haciendo Monitor::Enter/Exit(lock); (obviamente usando una variable auxiliar para no caer en recursividad infinita). Se ve perfectamente con un ejemplo:

Código:
//fichero de cabecera (.h)

ref class prPrty
{
public:
prPrty();

Thread^ thMethod();
void thAux();
int getA();

private:

property int a{
int get(){
Monitor::Enter(lock);
Thread::Sleep(3000);
return __a;
Monitor::Exit(lock);
}

void set(int _a){
Console::WriteLine("sin lock");
Monitor::Enter(lock);
Console::WriteLine("con lock");
Thread::Sleep(3000);
__a = _a;
Monitor::Exit(lock);
}
}

int __a;

Object ^lock;
};

/*********************************/

//Fichero fuente (.cpp)

#include "prPrty.h"


prPrty::prPrty(){
this->lock = gcnew Object();
}

Thread^ prPrty::thMethod(){
Thread ^th = gcnew Thread(gcnew ThreadStart(this, &prPrty::thAux));
th->Start();
return th;
}

void prPrty::thAux(){
this->a = 20;
}

int prPrty::getA(){
int aux;
Console::WriteLine("\tEsperando para el lock...");
Monitor::Enter(lock);
Console::WriteLine("\tlock obtenido");
aux = a;
Monitor::Exit(lock);
return aux;
}

/*********************************/

//main (.cpp)

int main(){
prPrty ^a = gcnew prPrty();
Thread ^th=a->thMethod();
Thread::Sleep(500);
Console::WriteLine("\t\t"+a->getA());
th->Join();
Console::ReadLine();
return 0;
}

Espero que le sirva a alguien de algo, saludos.


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines