Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Otros entornos y lenguajes > C++ Builder
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 25-03-2014
Avatar de aguml
aguml aguml is offline
Miembro
 
Registrado: may 2013
Posts: 885
Poder: 12
aguml Va por buen camino
Problemas con los hilos en Builder

Hola amigos, aqui otra vez con problemas .
El problema que tengo ahora es que estoy probando el manejo de un hilo y si uso Terminate() y FreeOnTerminate = true le doy y se termina el hilo y se destruye pero, si uso Suspend() el hilo no se detiene y sigue trabajando. Probé a poner FreeOnTerminate = false y usar WaitFor() despues de Suspend(), Resume(), o Terminate() pero me encuentro con que ejecuta cualquiera de esas lineas y llega al WaitFor() y se queda congelado todo, tanto el interfaz como el hilo.
No se por qué pasa esto y ademas tuve que poner un Application->ProcessMessage() para que procese los mensajes y me deje trabajar sobre el form para poder pulsar los botones ya que si no es así no me deja hacer nada y el form se congela mientras corre el hilo ¿no se supone que los hilos son entre otras cosas para evitar eso?

Es muy cortito asi que lo pongo aquí:

THilo.cpp:
Código:
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "THilo.h"
#include "Unit1.h"
#pragma package(smart_init)

__fastcall THilo::THilo(bool CreateSuspended)
        : TThread(CreateSuspended)
{
        Priority = tpNormal;
        FreeOnTerminate = false;
}
//---------------------------------------------------------------------------
void __fastcall THilo::Execute()
{
        Synchronize(Bucle);
}
//---------------------------------------------------------------------------

void __fastcall THilo::Bucle()
{
        while(!Terminated)
        {
                Form1->Caption = Form1->Caption.ToDouble() + 1;
                Application->ProcessMessages();
                Sleep(1000);
        }
}
THilo.h:
Código:
//---------------------------------------------------------------------------

#ifndef THiloH
#define THiloH
//---------------------------------------------------------------------------
#include <Classes.hpp>
//---------------------------------------------------------------------------
class THilo : public TThread
{
private:
protected:
        void __fastcall Execute();

        void __fastcall THilo::Bucle();
public:
        __fastcall THilo(bool CreateSuspended);
};
//---------------------------------------------------------------------------
#endif
Unit1.cpp:
Código:
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include "THilo.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;

THilo *Hilo;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::ButtonCrearClick(TObject *Sender)
{
        Hilo = new THilo(false);
        ButtonCrear->Enabled = false;
        ButtonPausa->Enabled = true;
        ButtonAbortar->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::ButtonContinuarClick(TObject *Sender)
{
        Hilo->Resume();
        Hilo->WaitFor();
        ButtonContinuar->Enabled = false;
        ButtonPausa->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ButtonPausaClick(TObject *Sender)
{
        Hilo->Suspend();
        Hilo->WaitFor();
        ButtonContinuar->Enabled = true;
        ButtonPausa->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ButtonAbortarClick(TObject *Sender)
{
        Hilo->Terminate();
        Hilo->WaitFor();
        delete Hilo;
        ButtonCrear->Enabled = true;
        ButtonPausa->Enabled = false;
        ButtonContinuar->Enabled = false;
        ButtonAbortar->Enabled = false;
}
//---------------------------------------------------------------------------
Ya digo que es una prueba y que luego ya colocaria bien cosas que tengo como global y cosas asi. El caption del Form1 es 0.
Estas cosas no me pasan usando las Apis de windows ResumeThread(), SuspendThread(), CreateThread(), y TerminateThread() ¿por que pasa con el que nos da Borland?
Responder Con Cita
  #2  
Antiguo 25-03-2014
Avatar de aguml
aguml aguml is offline
Miembro
 
Registrado: may 2013
Posts: 885
Poder: 12
aguml Va por buen camino
Acabo de ver que es un problema con Synchronize(), o sea, si uso Synchronize no me funciona ni Resume(), ni Suspend(), WaitFor(). Pero creo que voy a necesitar del uso de Synchronize ¿como lo hago?
Responder Con Cita
  #3  
Antiguo 26-03-2014
Avatar de aguml
aguml aguml is offline
Miembro
 
Registrado: may 2013
Posts: 885
Poder: 12
aguml Va por buen camino
bueno ya lo conseguí. Me explicaron que es porque Synchronize es para sincronizar entre hilos y que no habia que usarlo para todo y despues de algunos cambios ya fue. Ahora me encuentro con otro problema, necesito pasar variables desde donde creo el hilo hasta el execute y que dichas variables esten accesibles en ambos sitios. No puedo usar variables globales. ¿Como le puedo pasar variables al hilo? Con THilo hilo = new *THilo() solo puedo pasarle el estado al crearse. Probé a pasarle mas variables modificandola en la clase y me daba un error sobre que estaba haciendo una funcion abstracta o algo asi.
Responder Con Cita
  #4  
Antiguo 27-03-2014
Avatar de aguml
aguml aguml is offline
Miembro
 
Registrado: may 2013
Posts: 885
Poder: 12
aguml Va por buen camino
Ahora me encuentro con otro problema, tengo usa serie de funciones en unit1 y quiero ejecutarlas desde el hilo pero por supuesto el hilo no sabe ni que existen ¿como hago para poder ejecutarlas desde el hilo?
Responder Con Cita
  #5  
Antiguo 27-03-2014
Avatar de escafandra
[escafandra] escafandra is offline
Miembro Premium
 
Registrado: nov 2007
Posts: 2.197
Poder: 20
escafandra Tiene un aura espectacularescafandra Tiene un aura espectacular
Cita:
Empezado por aguml Ver Mensaje
Ahora me encuentro con otro problema, tengo usa serie de funciones en unit1 y quiero ejecutarlas desde el hilo pero por supuesto el hilo no sabe ni que existen ¿como hago para poder ejecutarlas desde el hilo?
Incluye unit1 (#include unit1.h) en la unit donde esté tu TThread y usa Synchronize para ejecutarlas.

Saludos.
Responder Con Cita
  #6  
Antiguo 27-03-2014
Avatar de aguml
aguml aguml is offline
Miembro
 
Registrado: may 2013
Posts: 885
Poder: 12
aguml Va por buen camino
No me funciona o no se como hacerlo. Tengo esto en el Execute del hilo:

Código:
case EXCEPTION_SINGLE_STEP:
      if(FuncSingleStep != NULL)
      {
            try{
                  FuncSingleStep();
            }
            catch(...){
            }
      }

      dwContinueStatus = OnSingleStep(&DebugEv);
      break;

case EXCEPTION_GUARD_PAGE_VIOLATION:
     dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
     break;

y en el .h donde están las funciones tengo esto:

Código:
#include <vcl.h>
#include "THiloDebugger.h"

#ifndef DEBUGGERH
#define DEBUGGERH
#define EXCEPTION_GUARD_PAGE_VIOLATION 0x80000001L

//tipos de funciones eventos
typedef  void __fastcall(__closure* SYSTEMBREAKPOINT)(void);
typedef  void __fastcall(__closure* BREAKPOINT)(DWORD);
typedef  void __fastcall(__closure* EXCEPTION)(int,DWORD);
typedef  void __fastcall(__closure* CREATEPROCESS)(CREATE_PROCESS_DEBUG_INFO *);
typedef  void __fastcall(__closure* EXITPROCESS)(EXIT_PROCESS_DEBUG_INFO *);
typedef  void __fastcall(__closure* CREATETHREAD)(CREATE_THREAD_DEBUG_INFO *);
typedef  void __fastcall(__closure* EXITTHREAD)(EXIT_THREAD_DEBUG_INFO *);
typedef  void __fastcall(__closure* LOADDLL)(LOAD_DLL_DEBUG_INFO *);
typedef  void __fastcall(__closure* UNLOADDLL)(UNLOAD_DLL_DEBUG_INFO *);
typedef  void __fastcall(__closure* OUTPUTSTRING)(OUTPUT_DEBUG_STRING_INFO *);
typedef  void __fastcall(__closure* RIP)(RIP_INFO *);
typedef  void __fastcall(__closure* SINGLESTEP)(void);

typedef struct{
        SYSTEMBREAKPOINT FuncSystemBreakPoint;
        BREAKPOINT     FuncBPs;
        EXCEPTION     FuncException;
        CREATEPROCESS     FuncCreateProcess;
        EXITPROCESS     FuncExitProcess;
        CREATETHREAD     FuncCreateThread;
        EXITTHREAD     FuncExitThread;
        LOADDLL         FuncLoadDLL;
        UNLOADDLL     FuncUnLoadDLL;
        OUTPUTSTRING     FuncOutPutString;
        RIP         FuncRIP;
                SINGLESTEP       FuncSingleStep;
}TEventDebugCallBack;

   class TDebugger
   {

        //estructura debug_event requerida para obtener los eventos del proceso y poder gestionarlos

        public:
                //variable necesaria para salir cuando lo deseemos del bucle
                bool Terminated;
                                AnsiString PathFile;
                                bool DebugExists;

                TDebugger();
                ~TDebugger();
                bool InitDebug(void); //Carga la víctima
                void LoopDebug(void);  // inicio de la depuración

                // Solo tienen sentido si el depurador está parado
                AnsiString ReadString(DWORD, int);
                bool SetBP(DWORD);
                bool RemoveBP(DWORD);
                bool SetHBP(DWORD, int, int, int);
                bool RemoveHBP(int);
                bool RemoveAllHBP(void);

                DWORD GetEAX(void);
                DWORD GetECX(void);
                DWORD GetEDX(void);
                DWORD GetEBX(void);
                DWORD GetESP(void);
                DWORD GetEBP(void);
                DWORD GetESI(void);
                DWORD GetEDI(void);
                DWORD GetEIP(void);

                void SetSingleStep(void);
                DWORD GetLastAddress(void);

                void SetEAX(DWORD Valor);
                void SetECX(DWORD Valor);
                void SetEDX(DWORD Valor);
                void SetEBX(DWORD Valor);
                void SetESP(DWORD Valor);
                void SetEBP(DWORD Valor);
                void SetESI(DWORD Valor);
                void SetEDI(DWORD Valor);
                void SetEIP(DWORD Valor);

                // Establecer los CallBacks

                void SetOnSystemBreakPoint(SYSTEMBREAKPOINT);
                void SetOnBPs(BREAKPOINT);
                void SetOnException(EXCEPTION);
                void SetOnCreateProcess(CREATEPROCESS);
                void SetOnExitProcess(EXITPROCESS);
                void SetOnCreateThread(CREATETHREAD);
                void SetOnExitThread(EXITTHREAD);
                void SetOnLoadDll(LOADDLL);
                void SetOnUnLoadDll(UNLOADDLL);
                void SetOnOutPutString(OUTPUTSTRING);
                void SetOnRIP(RIP);
                                void SetOnSingleStep(SINGLESTEP);

                void SetCallBack(TEventDebugCallBack *);

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


      private:
                                BOOL SearchBPOnList(DWORD, BYTE *, int *, bool *);

                // Eventos del hilo de depuración
                DWORD OnCreateThreadDebugEvent(LPDEBUG_EVENT);
                DWORD OnCreateProcessDebugEvent(LPDEBUG_EVENT);
                DWORD OnExitThreadDebugEvent(LPDEBUG_EVENT);
                DWORD OnExitProcessDebugEvent(LPDEBUG_EVENT);
                DWORD OnLoadDllDebugEvent(LPDEBUG_EVENT);
                DWORD OnUnloadDllDebugEvent(LPDEBUG_EVENT);
                DWORD OnOutputDebugStringEvent(LPDEBUG_EVENT);
                DWORD OnRipEvent(LPDEBUG_EVENT);

                // tratamiento de excepciones
                DWORD OnSingleStep(LPDEBUG_EVENT);
                DWORD OnBreakpointDebugEvent(LPDEBUG_EVENT);

                        DWORD LastExceptionAddress;

      protected:

                //Para la gestion de los BPs
                TList *ListaBPs; //Lista para la gestion de las estructuras BP
                int pos; //Para recuperar la posicion que ocupa un BP en la lista
                bool estadoBP; //Lo uso para saber si el usuario quiso eliminar el BP de la lista
                DWORD FAddrOnBPSS; // Dirección del BP a restaurar en EXCEPTION_SINGLE_STEP
                BYTE bOriginal; //Lo uso para obtener el byte original de la posición del BP

                //Estructura para cada BP
                typedef struct TBP
                {
                        DWORD dir;
                        BYTE byteOriginal;
                        bool estado; //true activado, false desactivado
                }*pBP;

        //Estructura startup requerida para createprocess
        STARTUPINFO si;

        //estructura process information requerida para el pid
        PROCESS_INFORMATION pi;
        //estructura context contiene los valores de los registros

        #pragma align 8  // no recuerdo bien si esto se hace con un #pragma
        CONTEXT con;

        // Funciones de callback
        SYSTEMBREAKPOINT FuncSystemBreakPoint;
        BREAKPOINT     FuncBPs;
                SINGLESTEP       FuncSingleStep;
        EXCEPTION     FuncException;
        CREATEPROCESS     FuncCreateProcess;
        EXITPROCESS     FuncExitProcess;
        CREATETHREAD     FuncCreateThread;
        EXITTHREAD     FuncExitThread;
        LOADDLL         FuncLoadDLL;
        UNLOADDLL     FuncUnLoadDLL;
        OUTPUTSTRING     FuncOutPutString;
        RIP         FuncRIP;
   };

#endif
No consigo hacer que reconozca las funciones en el execute del hilo aunque tenga el .h en el archivo de cabecera del hilo y use synchronize ¿como tengo que hacerlo para que funcione bien y compile?
En lo que pongo arriba no me reconocería ni FuncSingleStep, ni FuncSingleStep(), ni OnSingleStep(&DebugEv) pero me pasa igual con todas las demás.
He probado cosas como:

Synchronize(dwContinueStatus = TDebugger::OnExitProcessDebugEvent(&DebugEv));

pero creo que esto no explota de milagro jajaja. Ya no se que probar.

Última edición por aguml fecha: 27-03-2014 a las 15:01:12.
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Problemas con hilos y remobjects Pascal Script. J.Slann Varios 4 19-11-2011 17:35:28
Problemas con acceso telefonico a redes e hilos ospaco69 OOP 0 08-08-2007 00:02:36
problemas con hilos (Thead) jmlifi Varios 2 20-03-2007 17:56:53
problemas con Hilos (Thread) jmlifi Varios 2 26-02-2007 15:29:21
Builder c++ 6 y los hilos javikanin C++ Builder 1 26-11-2004 14:49:10


La franja horaria es GMT +2. Ahora son las 11:55:32.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi