Search code examples
multithreadingc++buildervcl

In C++ Builder, how to execute a function inside a `TThread`?


I created a TThread using the File > New > Other > Thread Object menu. It gave me some boilerplate code, like this:

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

#include <System.hpp>
#pragma hdrstop

#include "Unit2.h"
#pragma package(smart_init)
//---------------------------------------------------------------------------

//   Important: Methods and properties of objects in VCL can only be
//   used in a method called using Synchronize, for example:
//
//      Synchronize(&UpdateCaption);
//
//   where UpdateCaption could look like:
//
//      void __fastcall MyThreadClass::UpdateCaption()
//      {
//        Form1->Caption = "Updated in a thread";
//      }
//---------------------------------------------------------------------------

__fastcall MyThreadClass::MyThreadClass(bool CreateSuspended)
    : TThread(CreateSuspended)
{
}
//---------------------------------------------------------------------------
void __fastcall MyThreadClass::Execute()
{
    NameThreadForDebugging(System::String(L"MyThread"));
    //---- Place thread code here ----
    ShowMessage("Hello World!");
}
//---------------------------------------------------------------------------

header

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

#ifndef Unit2H
#define Unit2H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
//---------------------------------------------------------------------------
class MyThreadClass : public TThread
{
protected:
    void __fastcall Execute();
public:
    __fastcall MyThreadClass(bool CreateSuspended);
};
//---------------------------------------------------------------------------
#endif

I added the line you can see, ShowMessage("Hello World!"), and ran the program, but nothing happens besides my form being displayed.

How do I execute the code inside my thread function?


Solution

  • I had to replace the ShowMessage("Hello World!") line with this:

    Synchronize([](){ ShowMessage("Hello World!"); });
    

    And create the thread with this:

    MyThreadClass* myThread = new MyThreadClass(false); // false == don't create suspended