RTL.Threads Sample

From RAD Studio Code Examples
Jump to: navigation, search



This demo exemplifies the use of threads in a sample application that compares the speed of three different sorting algorithms: BubbleSort, QuickSort, and SelectionSort, which are executed in three separate threads.


You can find the thrddemo sample project at:


The application creates a form with three TPaintBoxes corresponding to the three sorting algorithms. Each paint box contains the visual representation of a randomized array. The Start Sorting button creates the corresponding threads that will sort the array. The form is being updated as the algorithms execute.

How to Use the Sample

  1. Navigate to Start | Programs | Embarcadero RAD Studio XE6 | Samples and open thrddemo.dproj.
  2. Press F9 or choose Run > Run.

Freezing and thawing threads using the THRDDEMO Sample Project

The thrddemo project contains three named threads (TBubbleSort, TQuickSort, and TSelectionSort).

  1. Click Start | Programs | Embarcadero RAD Studio XE6 | Samples to find the thrddemo.dproj sample.
  2. In the Project Manager, open the SortThds.pas file.
  3. In the Code Editor, find (Ctrl+F) the following source line:
    Sort(Slice(FSortArray^, FSize));
  4. Click the gray gutter column to set a breakpoint (Breakpoint.bmp) on that code line.
  5. Press F9 or choose Run > Run to run the program.
  6. In the Thread Sorting Demo window, click Start Sorting. Processing stops at the line containing the breakpoint.
  7. Open the Thread Status window using either View > Debug Windows > Threads or CTRL+ALT+T.
  8. Notice that the thread named TBubbleSort is in Stopped state, with the Status showing Breakpoint.
  9. Press F9 again, and notice that the TQuickSort thread was created and is in the same state as TBubbleSort.
  10. Press F9 again, and notice that now the TSelectionSort thread was created and is in the same state as the other two threads.

You can now freeze any of the threads and run the other threads to demonstrate freezing. After a thread is frozen, you can then thaw the thread.


File Contains


The classes for the three threads.


The code for the main form.


  • TSortThread, derived from TThread, provides an Execute method, a virtual Sort method and handles the repainting of the form as the sort algorithms execute.
  • TBubbleSort, TSelectionSort, and TQuickSort inherit from TSortThread and implement the corresponding Sort algorithm.
  • TThreadFormSort, the class corresponding to the form, manages the three threads, randomizes the array that will be sorted, and paints it in the corresponding paint boxes.


Note: The method that repaints the form (DoVisualSwap) must not be called directly because it uses a VCL component, and multithread conflicts can arise. Instead, DoVisualSwap should be passed to the Synchronize method, which causes the method to be executed by the main VCL thread.


See Also

Personal tools