// File H
#include <windows.h>
// Costanti
const int MAX_THREAD = 100; // Il massimo di thread che puoi gestire
// Variabili
HANDLE Thrd[MAX_THREAD]; // Handle
DWORD ThrdId[MAX_THREAD]; // Il tipo DWORD corrisponde ad un INT
// Prototipi
int threadError( int errorCode ); // Mostra un messaggio d'errore
bool createThread( void (*method)(), int id ); // crea un nuovo thread
bool suspendThread( int id ); // sospende un thread
bool terminateThread( int id ); // termina un thread
bool waitForThread( int id, int time ); // aspetta la fine di un thread
// Messaggio d'errore
int threadError( int errorCode )
{
// Variabili
char* applicationName = "Karonte";
// Controlliamo di che errore si tratta
if( errorCode == 1 ) { MessageBox(NULL,"Errore nella creazione del Thread",applicationName,MB_OK|MB_ICONERROR); return errorCode; }
if( errorCode == 2 ) { MessageBox(NULL,"Errore nella sospensione del Thread",applicationName,MB_OK|MB_ICONERROR); return errorCode; }
if( errorCode == 3 ) { MessageBox(NULL,"Errore nella chiusura del Thread",applicationName,MB_OK|MB_ICONERROR); return errorCode; }
if( errorCode == 4 ) { MessageBox(NULL,"Errore nell' attendere la fine del Thread",applicationName,MB_OK|MB_ICONERROR); return errorCode; }
// Non restituisce errori
return(0);
}
// Crea un nuovo thread
bool createThread( void (*method)(), int id )
{
// Crea un thread
Thrd[id] = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)method, 0, 0, &ThrdId[id] );
// Se il thread e' stato creato restituisce true, altrimenti false.
return( Thrd[id] ? true : false );
}
// Sospende un thread
bool suspendThread( int id )
{
// Sospende il thread in base all' handle
int r = SuspendThread( Thrd[id] );
// Se il thread e' stato sospeso restituisce true, altrimenti false.
return( r ? true : false );
}
// Termina un thread
bool terminateThread( int id )
{
// Exit code
int exitCode = 0;
// Sospende il thread in base all' handle
int r = TerminateThread( Thrd[id], exitCode );
// Se il thread e' stato terminato restituisce true, altrimenti false.
return( r ? true : false );
}
// Aspetta la fine di un thread
bool waitForThread( int id, int time )
{
// Aspetta la fine di un thread in base all' handle
int r = WaitForSingleObject( Thrd[id], time );
// Se la funzione ha successo restituisce true, altrimenti false.
return( r ? true : false );
}