//Global variables
int Count;
HANDLE hCountUp, hCountDown;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
//Clear the memo box
mMessage->Lines->Clear();
//Set count to zero
Count = 0;
//Create the count up event as auto-reset and signalled
hCountUp = CreateEvent(NULL, FALSE, TRUE, NULL);
//Create the count down event as auto-reset and un-signalled
hCountDown = CreateEvent(NULL, FALSE, FALSE, NULL);
//Create the thread to count up
UpThread = new TCounterThread(TRUE);
//Create the thread to count down
DownThread = new TCounterThread(FALSE);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormDestroy(TObject *Sender)
{
//Terminate the count up thread
UpThread->Terminate();
//Terminate the count down thread
DownThread->Terminate();
//Close the count up event
CloseHandle(hCountUp);
//Close the count down event
CloseHandle(hCountDown);
}
//---------------------------------------------------------------------------
__fastcall TCounterThread::TCounterThread(bool TheCountUp) : TThread(TRUE)
{
//Tell the object to free itself once it is terminated
FreeOnTerminate = TRUE;
//Remember whether we are counting up or down
CountUp = TheCountUp;
//Resume execution of the thread
Resume();
}
//---------------------------------------------------------------------------
void __fastcall TCounterThread::Execute(void)
{
//As long as the thread is not terminated
while (!Terminated)
{
//If this is the count up thread
if (CountUp)
//Wait for the count up event to be raised
WaitForSingleObject(hCountUp, INFINITE);
//Otherwise, this is the count down thread
else
//Wait for the count down event to be raised
WaitForSingleObject(hCountDown, INFINITE);
//If this is the count up thread
if (CountUp)
{
//Add 10 to count
Count += 10;
//Wait 1000 milliseconds
Sleep(1000);
//Update the screen
Synchronize(UpdateDisplay);
//Raise the count down event
SetEvent(hCountDown);
}
//Otherwise, this is the count down thread
else
{
//Subtract 10 from count
Count -= 10;
//Wait 1000 milliseconds
Sleep(1000);
//Update the display
Synchronize(UpdateDisplay);
//Raise the count up event
SetEvent(hCountUp);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TCounterThread::UpdateDisplay(void)
{
//If there are too many memo lines, clear it
if (Form1->mMessage->Lines->Count > 200)
Form1->mMessage->Lines->Clear();
//Write the appropriate message depending on which thread this is
if (CountUp)
Form1->mMessage->Lines->Add("Count up thread " + IntToStr(Count));
else
Form1->mMessage->Lines->Add("Count down thread " + IntToStr(Count));
}
//----------------------------------------------------------------------------