function IsMultiThread : Boolean;
Description
The IsMultiThread function returns true when there is at least one thread running in addition to the main line of execution.
Threads are a complex matter (the example is a very simple example, but is still not so short), and beyond detailed discussion here.
Threads can be started using BeginThread as in the example, or using the TThread class.
Related commands
BeginThread Begins a separate thread of code execution
EndThread Terminates a thread with an exit code
ThreadVar Defines variables that are given separate instances per thread
Example code : A simple example
// Full Unit code.
// -----------------------------------------------------------
// You must store this code in a unit called Unit1 with a form
// called Form1 that has an OnCreate event called FormCreate.
unit Unit1;
interface
uses
Forms, Dialogs, Windows, SysUtils;
type
TMsgRecord = record
msg : string[30];
end;
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
end;
var
Form1: TForm1;
Implementation
{$R *.dfm} // Include form definitions
ThreadVar // We must allow each thread its own instances
// of the passed record variable
msgPtr : ^TMsgRecord;
// Private thread procedure to show a string
function ShowMsg(Parameter : Pointer) : Integer;
begin
// Set up a 0 return value
Result := 0;
// Map the pointer to the passed data
// Note that each thread has a separate copy of msgPtr
msgPtr := Parameter;
// Display this message
ShowMessagePos('Thread message : '+msgPtr.msg, 200, 100);
// End the thread
EndThread(0);
end;
procedure TForm1.FormCreate(Sender: TObject);
var
id1 : LongWord;
thread1 : Integer;
msg1 : TMsgRecord;
showMsgFunc : TThreadFunc;
begin
// Set up the thread function
showMsgFunc := Addr(ShowMsg);
// Set up our display messages
msg1.msg := 'Hello World';
// Inidicate that we are not running a thread
if IsMultiThread
then ShowMessage('Multi-threaded')
else ShowMessage('Single threaded');
// Start the first thread running asking for users first name
thread1 := BeginThread(nil,
0,
showMsgFunc,
Addr(msg1),
0,
id1);
// Inidicate that we are running a thread
if IsMultiThread
then ShowMessage('Multi-threaded')
else ShowMessage('Single threaded');
// Ensure that the thread is only closed when all done
ShowMessagePos('Press this when thread dialog finished.', 200, 300);
// Finally, tidy up by closing the threads
CloseHandle(thread1);
end;
end.
A sequence of dialogs is displayed:
Single threaded
Multi-threaded + Thread message : Hello World
Press this when the thread dialog finished.