#define INCL_DOSPROCESS
#define INCL_DOSMODULEMGR

#include <stdlib.h>

#include "xthread.h"
#include "xmsgbox.h"

int XThread :: threadsRunning = 0;

/*DOC
CLASS XThread
FUNCTION Terminate
GROUP initiate/terminate a process
REMARKS With this method a thread can be terminated. If you
call Terminate() the method QueryForQuit() will not be called.

Parameters:    -
Returns:       -
*/
void XThread :: Terminate( void )
{
   XProcess::Terminate();
   threadsRunning-=1;
   _endthread();
}


void XThread :: ThreadEntry( void )
{
   hab = WinInitialize(0);
   queue = WinCreateMsgQueue( hab, 0);
   Init();
   Start();
}


/*DOC
CLASS XThread
FUNCTION XThread
GROUP constructors/destructors
REMARKS contructs a thread. After a thread is constructed, call Run() to make
the thread work. You can override method Init() where you can construct
windows and so on. After you have called Run() for one or more threads,
you must call RunThreads() to initialize this threads (only one time
required).
WARNING: donīt try to construct windows in the constructor of XThread or a derived
class of it! At this time it is not posssible to start threads from a XApplication.
To start a thread the starting process must be a thread too.
Parameters:    -
Returns:       -
*/
XThread::XThread()
{

}

//void XThread :: StartUp(void * v)
void _Optlink StartUp(void * v)
{
   XThread * t = (XThread * ) v;
   XThread::threadsRunning++;
   t->ThreadEntry();
   delete t;
}


void XThread :: Init(void)
{ ;}


void XThread::Run()
{
  TID tid;

  #ifdef __BCPLUSPLUS__
    tid=_beginthread( StartUp(this), 64000, this);
  #else
    tid=_beginthread( StartUp, 0, 64000, (void*) this);
  #endif
  if( tid == -1 )
     XMessageBox( "couldnīt create a thread" );

}


/*DOC
CLASS XThread
FUNCTION RunThreads
GROUP initiate/terminate a process
REMARKS call RunThreads if you have constructed one or more threads.
Call RunTreads only one time.

Parameters:    -
Returns:       -
*/
void XThread :: RunThreads( void )
{
  while (1)
   {
     TID id=0;
     DosWaitThread(&id, DCWW_WAIT);
     if ( XThread::threadsRunning<=0)
        break;
     DosSleep(0);
   }
}


