Embarcadero TThread Just Works

I've been annoyed for a large amount of time (years in fact) over some of our software we use and sell. In essence, what we have is a TCP GUI that communicates on a 250ms timer with a microcontroller that's serving up a two-way communications protocol over ModBus FC23 - we send commands either to write data to or read data from the unit.

The developer we had make the initial software for us decided to use Embarcadero's system timer object to control the 250ms polling. Not only that, but I had to put in an 8-second delay during socket initialization (via a TPing object) in the event that the unit was rebooted (we want to wait until the unit can finish booting before we say that it can't be found on the network). And I learned ALL of my Borland/Embarcadero, and even the majority of my C++ knowledge from this program and others I've patterned after it.

But both the timer and the timeout exist in the main method. So every time the TPing object waits for the unit's response, or every time the 250ms timer hung, the entire program would freeze. It's been very annoying to say the least.

The microcontroller library I use (Netburner uCOS) has a fairly straightforward way to set up "tasks," and particularly the MOD5282 has something called a periodic interrupt (PITR) which will run a very fast clock at some hardware-programmable rate that will set an IRQ interrupt flag (and hardware pin) every time it fires. These two things are really cool because not only do I have a very fast and very calibrated clock that I can run certain tasks on at a rapid rate, but I can do so within separate tasks which keep the entire program from freezing if set up correctly.

But it required a slight change in thinking. I cannot run intensive processing within the PITR (printf(), etc). I cannot use OSTimeDly(n) (essentially the Sleep() function of uCOS, which is also limited to 20ms minimum) within the PITR. And I cannot utilize critical sections or OSLock() for any more than a few essential operations at a time. Otherwise the watchdog timer of the microcontroller could hang and force it to reboot.

I also have to explicitly declare a task's stack memory on the Netburner and have to give each some priority to make sure that more important tasks continue to run properly.

Thing is, Netburner's documentation on Tasks is quite good once you know where to look.

Embarcadero's documentation is a bit more confusing.

Borland/Embarcadero uses something called the TThread class. I figured multithreading a GUI application would be simple - simply declare a "task," set it up to run by itself using numerous different parameters with timers and what-not. Not according to documentation.

According to documentation you have to set up an entirely separate TThread class and you have to Synchronize objects from the main form in order to change their values. And none of the example programs look very straightforward.

Of course, the only example program I have is some triple-sorting GUI with three threads other than the main one, each sorting a set of data with a different algorithm. Out of the box, it's really cool. You hit the button and watch the three bar graphs simultaneously sort themselves from high values to low values, some taking longer than others. A great example program.

But I don't do any sorting in my programs. All I WANT is to push a button in my GUI and have it attempt to connect to a remote unit for eight seconds without hanging. Meaning, if I know it's not there, I can simply push the disconnect button and cancel it. Or close the GUI completely because I realize I made some mistake in programming.

In short, MY need for multithreading exists on a much simpler level. I want to be able to interrupt something that would otherwise force me to wait, since it emulates the Sleep() function.

Then I figured it out. Threading is still my solution. Only getting it set up in the Embarcadero IDE is much much simpler than the scant documentation and example programs would lead you to believe.

Here's my example program:
1. Create a simple VCL form with a TLabel (or any other object that takes a String input and displays it).

2. Drop a TSpeedButton object, setting its GroupIndex to a positive integer (like 1) and setting its AllowAllUp property to true. Now we have a toggle switch.

3. Create a global bool variable and give it some name like "ThreadExecute."

4. Bind the OnClick event of the TSpeedButton to some function, namely its default "SpeedButton1Click(TObject *Sender)" and tell it to toggle the global boolean set in step 3 based on its Down boolean property:
void __fastcall TForm1::SpeedButton1Click(TObject *Sender) {
  // This ensures that the SpeedButton1->Down status is available globally for other things, such as the other thread.
  ThreadExecute = SpeedButton1->Down;
}

5. Now for the super simple part - File > New > Other > C++ Builder Files > Thread Object. This will create a new unit, a cpp and h file set with the same name that act like a single "unit" (hence the name) within the IDE. The class it automatically creates will be assigned to the TThread class type, just like the main form is assigned to the TForm class type. It will also create two default functions - a constructor for initializing internal variables or what-not when a TThread object of this class is created, and an Execute() function for when the thread is "started."

6. In the TThread::Execute() function, create some iterative process, like adding 1 to a number within an endless while loop:
int n = 0;

void __fastcall ThLooper::Execute() {
  // Note - A while(1) loop, particularly with a Sleep() delay at the end would most certainly freeze the main loop and make it unresponsive to any further user interaction.
  while (1) {
    // Only execute if Toggle button in the Main form is Down.
    if (ThreadExecute) {
      n++;
    }
    Sleep(250);  } // end while
}

7. In the main form, set up the TForm's constructor to initialize the Thread in its own object:
ThLooper *Thread1;
__fastcall TForm1::TForm1(TComponent *Owner) : TForm(Owner) {
  Thread1 = new ThLooper(true); // Note - the CreateSuspended parameter creates the Thread object without starting it automatically.
  Thread1->Start(); // Can also use Resume(). This is needed if the Thread was created with CreateSuspended == true.
}
8. We now will probably need to display the value of n in the main form. However note the comment in the Thread class file - "Methods and properties of objects in VCL can only be used in a method called using Synchronize." This means you must use the Synchronize() function in order to access Form1 objects like the Label we want to update the caption of:
int n = 0;
// Should declare this first. Can be done in the thread header file.
void __fastcall ThLooper::UpdateLabel(void);


void __fastcall ThLooper::Execute() {
  while (1) {
    if (ThreadExecute) {
      n++; // Note - we made this global to access it from a synchronize method call.
      Synchronize(&UpdateLabel);
    }
    Sleep(250);
  } // end while
}

void __fastcall ThLooper::UpdateLabel() {
  Form1->Label1->Caption = (String)"N=" + n;

}

And that's it! That's all I needed to do to set up a thread that runs a constant process that would normally freeze the program outright. I can start the timer, or stop it using the toggle button, but the endless while loop will not freeze any portion of the main thread.

Looking at the documentation, there are also properties for setting a thread's priority to low or high, set it to destroy itself on an exception, and numerous other things.

And my knowledge of Netburner tasks simply verifies what I already know when Embarcadero highlights the following things to be aware of:
1. Too many threads consumes CPU time - limit yourself to 16 threads per CPU processor.
2. If multiple threads access the same resources, they must be synchronized to avoid conflict.
3. Updates to the form must be limited to the main thread. Updating a form element from within a thread should be done via thread synchronization such as TMultiReadExclusiveWriteSynchronizer.

This subject is not as complex as I had first believed!

Official Documentation:

Example.h:

#ifndef ExampleH
#define ExampleH

#include
#include
#include
#include
#include

class TForm1 : public TForm {
__published:    // IDE-managed Components
    TLabel *Label1;
    TSpeedButton *SpeedButton1;
    void __fastcall SpeedButton1Click(TObject *Sender);
    void __fastcall FormShow(TObject *Sender);
private:    // User declarations
public:        // User declarations
    __fastcall TForm1(TComponent* Owner);
};

extern PACKAGE TForm1 *Form1;

#endif


Example.cpp:

#include
#pragma hdrstop

#include "Example.h"
#include "ThLooper.h"

#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
ThLooper *Looper;

__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) {
    Looper = new ThLooper(true); // Initially suspended. We don't want to risk updating VCL components before they are completely created.
}

void __fastcall TForm1::FormShow(TObject *Sender) {
    Looper->Start(); // VCL Form has been fully created. Can now start Looper thread.
}

void __fastcall TForm1::SpeedButton1Click(TObject *Sender) {
    Label1->Caption = (SpeedButton1->Down)?"Running":"Halted";
    Looper->Go = SpeedButton1->Down;
}



ThLooper.h:

#ifndef ThLooperH
#define ThLooperH
#include

class ThLooper : public TThread {
private:
  void __fastcall UpdateLabel(void);
  void __fastcall AnimateStatus(void);
protected:
  void __fastcall Execute();
public:
  __fastcall ThLooper(bool CreateSuspended);
  bool Go;
};

#endif


ThLooper.cpp:

#include
#pragma hdrstop

#include "Example.h" // To update VCL form elements.
#include "ThLooper.h"
#pragma package(smart_init)

// AnimateStatus is a quick little text-based progress bar I made.
char ConnAniCtr = 0;
char ConnAniMax = 4;
char ConnAniDelay = 2;
char ConnAniDelayCtr = 0;
String ConnAni = "";
short N = 0;
void __fastcall ThLooper::AnimateStatus() {
  if (ConnAniDelayCtr < ConnAniDelay)
    ConnAniDelayCtr++;
  else {
    ConnAniDelayCtr = 0;
    if (ConnAniCtr >= ConnAniMax)
      ConnAniCtr = 0;
    else
      ConnAniCtr++;
  } // if

  ConnAni = StringOfChar('.',ConnAniCtr);
  Synchronize(&UpdateLabel); // Synchronously update VCL Form Label.
}

__fastcall ThLooper::ThLooper(bool CreateSuspended) : TThread(CreateSuspended) {
    Go = false; // Do not run initially.
}

void __fastcall ThLooper::Execute() {
  while (1) {
    if (Go) {
        AnimateStatus();
        N++;
    }
    Sleep(250); // Can comment this to see max speed of thread. Synchronize does not significantly pause thread execution.
  }
}

void __fastcall ThLooper::UpdateLabel() {
  Form1->Label1->Caption = (String)"Running" + N + ConnAni;
}

No comments :

Post a Comment

Comment loud, comment often. But comment on the content!

All comments are filtered through to my email, so your spam will never make it. Unless, of course, you wanted to try injection attacks into my email, which would probably not happen since Blogger just tells me that a comment is awaiting moderation and doesn't bother to tell me what it says. I trust Blogger like that..