Snapshot: Hilos en C++ (Windows)

by Jorge Machin on September 26, 2008 · 0 comments

in C/C++, Programación, Snapshots, Windows

Una clase "quick and dirty" para crear hilos en cajas windows.

Encabezado:

#pragma once

#include <windows.h>

class CThread {

   public:

      // Constructor por defecto:

      CThread(void);

      // Destructor virtual
   
      virtual ~CThread(void);

      // Esta función inicia el hilo:

      bool start();

      // Esta función se debe sobrecargar con lo que tiene que hacer el hilo:

      virtual void run() = 0;

      // Esta función espera a que el hilo se detenga. Se debe llamar en el destructor de la clase derivada.

      void join();

   private:

      unsigned long id;

      void *threadHandle;

      static DWORD WINAPI entryPoint( void *pthis );

};

Archivo cpp:

#include "StdAfx.h"
#include "thread.h"

CThread::CThread(void) : threadHandle( NULL ) {

   MessageBox( NULL, "CThread::CThread", "Aviso", MB_OK );

}

DWORD WINAPI CThread::entryPoint( void *pthis ) {

   CThread *pt = ( CThread * ) pthis;
   pt -> run();
   return 0;

}

bool CThread::start() {

   threadHandle = CreateThread( NULL, 0, ( LPTHREAD_START_ROUTINE ) entryPoint, this, 0, &id );
   return true;

}

void CThread::join() {

   if ( threadHandle != NULL )

      WaitForSingleObject( threadHandle, INFINITE );

}

CThread::~CThread(void) {

   MessageBox( NULL, "CThread::~CThread", "Aviso", MB_OK );

   if ( threadHandle != NULL )   

      CloseHandle( threadHandle );

}

Como se dislumbra de los comentarios, para utilizarla es necesario crear una clase que herede de Cthrean y sobrecargar la función run con lo que debe hacer nuestro hilo.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous post:

Next post: