//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "EnumeratorThread.h"
#pragma package(smart_init)

// BeginExample: ThreadSynchronize
// Method: Classes.TThread.Synchronize
// Method: Classes.TThread.WaitFor

// BeginCode
/*
This example demonstrates the use of Synchronize method to execute a procedure
on the main thread that "owns" the GUI. Also WaitFor is used to wait for the
thread's termination.
*/
__fastcall TEnumeratorThread::TEnumeratorThread(TMemo* Memo)
	: TThread(true)
{
	/* Initialize internal fields */
	m_Memo = Memo;
	m_CurrNbr = 0;
	m_Stop = 0;
}

void __fastcall TEnumeratorThread::Execute()
{
	/* Repeat the loop until the flag says otherwise */
	while (!m_Stop)
	{
		/* Wait for 100 milli */
		Sleep(100);

		/*
		Run AddNewNumberToMemo procedure on the main thread - makes
		it safe to access GUI from this thread.
		*/
		Synchronize(AddNewNumberToMemo);
	}

	m_Stop = 0;
}

void __fastcall TEnumeratorThread::GentleStop()
{
  /* Set the flag to 1 */
  InterlockedIncrement(&m_Stop);

  /* Wait for this thread to finish executing */
  this->WaitFor();
}

void __fastcall TEnumeratorThread::AddNewNumberToMemo()
{
  /* Increase current number and add it to the memo */
  m_CurrNbr++;
  m_Memo->Lines->Add(IntToStr(m_CurrNbr));
}

// EndCode
// EndExample: ThreadSynchronize
//---------------------------------------------------------------------------

