Initializing a Thread

From RAD Studio
Jump to: navigation, search

Go Up to Building a Multithreaded Application


To initialize a thread object

  1. Assign a default thread priority.
  2. Indicate when the thread is freed.

To assign a default priority

  1. Assign a default priority to the thread from the values listed in the table below.Use a high-priority to handle time critical tasks, and a low priority to perform other tasks.

Value

Priority

tpIdle

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

tpLowest

The thread's priority is two points below normal.

tpLower

The thread's priority is one point below normal.

tpNormal

The thread has normal priority.

tpHigher

The thread's priority is one point above normal.

tpHighest

The thread's priority is two points above normal.

tpTimeCritical

The thread gets highest priority.

  1. Override the Create method (Delphi) or default constructor (C++) of the thread class by adding a new constructor to the declaration.
  2. Code the constructor. The following is an example for a low-priority thread:
  3. constructor TMyThread.Create(CreateSuspended: Boolean);
    begin
      inherited Create(CreateSuspended);
      Priority := tpIdle;
    end; 
    
    TMyThread::TMyThread( bool CreateSuspended ) : TThread( CreateSuspended ) {
      Priority = tpIdle;
    }
    
  4. Indicate whether the thread should be freed automatically when it finishes executing.

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.

To indicate when a thread is freed

  1. Set the FreeOnTerminate property to true, unless the thread must be coordinated with other threads.
  2. If the thread requires coordination with another thread, set FreeOnTerminate to false; then explicitly free the first thread from the second.

See Also