ThreadSynchronize (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Language:

Description

This example demonstrates the use of the 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.

Code

__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 milliseconds. */
                Sleep(100);
 
                /*
                Run the AddNewNumberToMemo procedure on the main thread.
                This 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 the current number and add it to the memo. */
  m_CurrNbr++;
  m_Memo->Lines->Add(IntToStr(m_CurrNbr));
}

Uses

Personal tools