niedziela, 15 stycznia 2017

Using function BeginThread in C++ Builder




TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
HANDLE my_Event;
SECURITY_ATTRIBUTES my_attributes={sizeof(SECURITY_ATTRIBUTES),NULL,TRUE};
UINT my_ID;
LONG my_Thread=0;
 bool __fastcall is_First(int value)
 {
  int i,sum;
  sum=0;
  for(i=1;i<value+1;i++)
   if(value%i==0)
    ++sum;
  if(sum==2)
   return true;
  else
   return false;
 }
int __fastcall writeln_First(LPVOID value)
{
 int i;
 i=1;
 for(;;)
 {
  if(is_First(i))
   Form1->ListBox1->Items->Add(IntToStr(i));
  WaitForSingleObject((LPVOID)my_Thread,100);
  ++i;
 }
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
 ListBox1->Items->Clear();

}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
       ;
 my_Thread=BeginThread(&my_attributes,4096,writeln_First,this,CREATE_SUSPENDED,my_ID);
 if(my_Thread==(int)INVALID_HANDLE_VALUE)
 {
  ShowMessage("Thread error!");
 }
 else
 {
  ResumeThread((LPVOID)my_Thread);
  if(my_Event)
  {
   WaitForSingleObject(my_Event,150);
   CloseHandle(my_Event);
   Button1->Enabled=FALSE;
  }

 }

}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
 SuspendThread((LPVOID)my_Thread);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
 ResumeThread((LPVOID)my_Thread);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button4Click(TObject *Sender)
{
 CloseHandle((LPVOID)my_Thread);
 Close();
}

Brak komentarzy:

Prześlij komentarz