Initializing the Thread

From RAD Studio
Jump to: navigation, search

Go Up to Defining thread objects Index

If you want to write initialization code for your new thread class, you must override the Create method. Add a new constructor to the declaration of your thread class and write the initialization code as its implementation. This is where you can assign a default priority for your thread and indicate whether it should be freed automatically when it finishes executing.

Assigning a default priority

Priority indicates how much preference the thread gets when the operating system schedules CPU time among all the threads in your application. Use a high priority thread to handle time critical tasks, and a low priority thread to perform other tasks. To indicate the priority of your thread object, set the Priority property.

If writing a Windows-only application, Priority values fall along a scale, as described in the following table:

Thread priorities :

Value Priority


The thread executes only when the system is idle. Windows won't interrupt other threads to execute a thread with tpIdle priority.


The thread's priority is two points below normal.


The thread's priority is one point below normal.


The thread has normal priority.


The thread's priority is one point above normal.


The thread's priority is two points above normal.


The thread gets highest priority.

Warning: Boosting the thread priority of a CPU intensive operation may "starve" other threads in the application. Only apply priority boosts to threads that spend most of their time waiting for external events.

The following code shows the constructor of a low-priority thread that performs background tasks which should not interfere with the rest of the application's performance:

constructor TMyThread.Create(CreateSuspended: Boolean);
  inherited Create(CreateSuspended);
  Priority := tpIdle;
__fastcall TMyThread::TMyThread(bool CreateSuspended): TThread(CreateSuspended) {
    Priority = tpIdle;

Indicating when threads are freed

Usually, when threads finish their operation, they can simply be freed. In this case, it is easiest to let the thread object free itself. To do this, set the FreeOnTerminate property to True.

There are times, however, when the termination of a thread must be coordinated with other threads. For example, you may be waiting for one thread to return a value before performing an action in another thread. To do this, you do not want to free the first thread until the second has received the return value. You can handle this situation by setting FreeOnTerminate to False and then explicitly freeing the first thread from the second.

See Also