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

#include <vcl.h>
#pragma hdrstop

#include "WorkerThread.h"

//#pragma package(smart_init)
//---------------------------------------------------------------------------

  /*
   *Author  : 蕭沖 Xiao Chong
   *Email   : qs.xiao@gmail.com
   *Date    : 20060913
   *TODO    :
   *Compiler: BCB6
  **/
//---------------------------------------------------------------------------

__fastcall Worker::Worker(bool CreateSuspended)
  : TThread(CreateSuspended)
{
}
//---------------------------------------------------------------------------
void __fastcall Worker::Execute()
{
  extern TCriticalSection *gCS;
  WORK_ITEM item;
  while (!Terminated && WaitForSingleObject(MainForm->mDoWorkFlag,INFINITE)==0L)
  {
		gCS->Enter();  // 保護住
    item = MainForm->mQue.front(); //get the item from queue
		gCS->Leave();  // 釋放   // a ，移除這a行與下面的b行就會掛，因為下面那行tmemo用的是sendmessage
    item.mpFunction(item); //run user define function
		gCS->Enter();  // 保護住   // b 行，參照上面a行的解釋
    MainForm->mQue.pop_front();  //remove front queue item
		gCS->Leave();  // 釋放
    //VCL is not thread-safe comopnent, alter to MainForm execute
    //Synchronize(UpdateMemo);
    MainForm->Memo2->Lines->Delete(0);

    if (MainForm->mQue.size()==0) //if no work to do
      ::ResetEvent(MainForm->mDoWorkFlag);  //will stop at while

//    Sleep(500);
  }

}
//---------------------------------------------------------------------------

void __fastcall Worker::UpdateMemo(void)
{
    MainForm->Memo2->Lines->Delete(0); // delete first item from memo2
}
