#define INTHREADING
#include <Threading.h>

int ThreadCloseSelf( void )
{
pthread_t	selfid;
int		t=0,i=0,k=0;

selfid = pthread_self();

while ( t <= 4096 )
   {
   if ( ThreadDB[t].State == PT_RUNNING )
      {
      if ( ThreadDB[t].pID == selfid )
         {
         break;
         }
      }
   t++;
   }
if ( t > 4096 )
   return -1;

pthread_mutex_lock(&ThreadDB[t].Mutex);
ThreadDB[t].State = PT_CLOSING;
pthread_mutex_unlock(&ThreadDB[t].Mutex);
 
/*
   Give the thread some time to take care of
   business and close on its own */
while ( i <= 10 )
   {
   if ( ThreadDB[t].State == PT_CLOSED )
      return 0;
   i++;
   }    


pthread_mutex_lock(&ThreadDB[t].Mutex); ThreadDB[t].State = PT_FREE;
 
ThreadDB[t].WaitOnToExit = FALSE; 
ThreadDB[t].CurMsg = 0;
ThreadDB[t].ProcMsg = 0; 
while ( k <= 10 )
   {
   ThreadDB[t].MsgQue[k].State = PTM_FREE;
   ThreadDB[t].MsgQue[k].TimeStamp = 0;
   k++;
   }
 
pthread_mutex_unlock(&ThreadDB[t].Mutex);
 
/* Times up, kill the thread and reset the slot */
pthread_detach(ThreadDB[t].pID); 

return 0;
}
