Home Index

Multi Thread Programming in C++ Builder and Delphi
 
Date: Nov 01 2000
Subject: Online Programmer Ezine, Volume 1, No.2
Article: Multi Thread Programming in C++ Builder and Delphi

Have you ever written programs that their GUI stops to
respond because a process blocks program execution in a point
in your code? (For example blocking sockets)

If so, you can solve this problem with multi thread 
programming. Windows can run multiple paths in your program 
at once. So you can do your blocking operations in one thread
and GUI operations in main thread.

They will run without interrupting each other. Example 
program is written in C++ Builder but it can be ported to 
Delphi with small changes.

But be careful. Running VCL GUI codes are not thread safe so
we must run them inside a Synchronize() function call. This 
will run unsafe functions with threads in mind, so the result
is a safe code.

You can download both C++ Builder and Delphi source codes 
from this address :

 http://www.angelfire.com/nt/sarmadys/page3.html

and now the code ...

1- Create a normal project. Save Form1 unit as Unit1.

2- Add a new thread object (File->New->Thread Object. 
   Now save Thread unit as Unit2.

3- Unit1 code is : ( headers excluded )

 #include "Unit1.h"
 #include "Unit2.h"

 TForm1 *Form1;

 __fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
 {
 }

 void __fastcall TForm1::Button1Click(TObject *Sender)
 {
 TTestThread *MyThread=new TTestThread(False);
   //false starts thread on creation , True will suspend it
 }

4- Unit2 code is : ( headers excluded )

 #include "Unit2.h"
 #include "Unit1.h"
 #include "stdio.h"

 int gCounter;

 __fastcall TTestThread::TTestThread(bool CreateSuspended)
        : TThread(CreateSuspended)
 {
 }

 void __fastcall TTestThread::Execute()
 {
 int j;
 for(int i=0;i<100;i++)
   {
   Synchronize(UpdateTextBox);
   Sleep(1000);
   gCounter++;
   }
 }

 void __fastcall TTestThread::UpdateTextBox()
 {
  char temp[10];
  sprintf(temp,"%d",gCounter);
  Form1->Edit1->Text=temp;
 }

5- Now run program and test to see if main form stops to
   respond to your actions. It will not !. If you use 
   Sleep function in main thread ( main form ) in a loop , 
   Form1 will freeze. We used Sleep function in a separate
   thread therefore form will not freeze anymore.

As you see writing multi thread programs in C++ Builder and
Delphi is very easy. But know that writing thread programs
needs enough care. You must write thread safe code in thread
units. You must also prepare yourself for unordinary errors.

I wish this article be useful for those with complicated 
freezing programs !!!




Home Index
2000 OnlineProgrammer (HtmSoft.com). All Rights Reserved