Sign in Join
Wiki copytemporary

Multithreaded Application Tutorial: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Multithreaded Application Tutorial

OldNewLine
1+## Overview
2+
3+This page will try to explain how to write and debug a multi-threaded application with Free Pascal and Lazarus. A multi-threaded application is one that creates two or more threads of execution that work at the same time. If you are new to multi-threading, please read the paragraph "Do you need multi-threading?" to determine whether it is really required; this may save you many headaches.
4+
5+One of the threads is called the Main Thread. The Main Thread is the one that is created by the Operating System once our application starts. The Main Thread **must be** the only thread that updates the components that interfaces with the user: otherwise, the application may hang.
6+
7+The main idea is that the application can do some processing in background in a second thread while the user can continue working using the main thread.
8+
9+Another use of threads is just to have a better responding application. If you create an application, and when the user presses a button the application starts processing a big job... and while processing, the screen stops responding, and gives the user the impression that the application is frozen, a poor or misleading impression will be created. If the big job runs in a second thread, the application keeps responding (almost) as if it were idle. In this case it is a good idea, before starting the thread, to disable the buttons of the form to avoid the user starting more than one thread for the job.
10+
11+Another use of multi-threading may be a server application that is able to respond to many clients at the same time.
12+
13+## Do you need multi-threading?
14+
15+If you are new to multi-threading and you only want to make your application more responsive while your application performs moderately long-running tasks, then multi-threading may be more than is required. Multi-threaded applications are always more difficult to debug and they are often much more complex; in many cases you don't need multi-threading. A single thread is enough. If you can split up the time-consuming task into several smaller chunks, then instead you should use **Application.ProcessMessages**. This method allows the LCL to handle all waiting messages and returns. The central idea is to call Application.ProcessMessages at regular intervals during the execution of a long-running task to determine whether the user has clicked on something, or a progress indicator must be repainted, and so on.
16+
17+For example: Reading a big file and process it. See examples/multithreading/singlethreadingexample1.lpi.
18+
19+Multi-threading is only needed for
20+
21+- blocking handles, like network communications
22+- using multiple processors simultaneously (SMP)
23+- algorithms and library calls that must be called through an API and as such cannot be split up into smaller parts.
24+
25+If you want to use multi-threading to increase speed by using multiple processors simultaneously, check if your current program now uses all 100% resources of 1 core CPU (for example, your program can actively use input-output operations, e.g. writing to file; this takes a lot of time, but doesn't load CPU; in this case your program will not be faster with multiple threads). Also check if optimisation level is set to maximum (3). When switching optimisation level from 1 to 3, a program may become about 5 times faster.
26+
27+## Units needed for a multi-threaded application
28+
29+You don´t need any special unit for this to work with Windows. However with Linux, macOS and FreeBSD, you need the cthreads unit and it *must* be the first used unit of the project (the program source, usually the .lpr file)! In cases where several units like cthreads, cmem and cwstrings are recommended to be placed first, due to how the units work a sensible order is cmem, cthreads and then cwstrings.
30+
31+So, your Lazarus application code should look like:
32+
33+``` pascal
34+program MyMultiThreadedProgram;
35+{$mode objfpc}{$H+}
36+uses
37+{$ifdef unix}
38+ cthreads,
39+ cmem, // the c memory manager is on some systems much faster for multi-threading
40+{$endif}
41+ Interfaces, // this includes the LCL widgetset
42+ Forms
43+ { you can add units here },
44+```
45+
46+If you forget this and you use TThread you will get this error on startup:
47+
48+` This binary has no thread support compiled in.`\
49+` Recompile the application with a thread-driver in the program uses clause before other units using thread.`
50+
51+> **Note:** If you get a Linker error about "mcount" not found. Then you use some unit that contains some multithreaded code and you need to add the cthreads unit or use [[smart linking]].
52+
53+> **Note:** If you get the error: "Project raised exception class 'RunError(232)'" in procedure SYSTEM_NOTHREADERROR then your code requires threading and you need to add the cthreads unit.
54+
55+## Pure FPC example
56+
57+Below code gives a very simple example. Tested with FPC 3.0.4 on Win7.
58+
59+``` pascal
60+Program ThreadTest;
61+{test multi threading capability }
62+{
63+ OUTPUT
64+thread 1 started
65+thread 1 thri 0 Len(S)= 1
66+thread 1 thri 1 Len(S)= 2
67+thread 1 thri 2 Len(S)= 3
68+thread 1 thri 3 Len(S)= 4
69+thread 1 thri 4 Len(S)= 5
70+thread 1 thri 5 Len(S)= 6
71+thread 1 thri 6 Len(S)= 7
72+thread 1 thri 7 Len(S)= 8
73+thread 1 thri 8 Len(S)= 9
74+thread 1 thri 9 Len(S)= 10
75+thread 1 thri 10 Len(S)= 11
76+thread 1 thri 11 Len(S)= 12
77+thread 1 thri 12 Len(S)= 13
78+thread 1 thri 13 Len(S)= 14
79+thread 1 thri 14 Len(S)= 15
80+thread 2 started
81+thread 3 started
82+thread 1 thri 15 Len(S)= 16
83+thread 2 thri 0 Len(S)= 1
84+thread 3 thri 0 Len(S)= 1
85+thread 1 thri 16 Len(S)= 17
86+...
87+...
88+thread 5 thri 997 Len(S)= 998
89+thread 5 thri 998 Len(S)= 999
90+thread 5 thri 999 Len(S)= 1000
91+thread 5 finished
92+thread 10 thri 828 Len(S)= 829
93+thread 9 thri 675 Len(S)= 676
94+thread 4 thri 656 Len(S)= 657
95+thread 10 thri 829 Len(S)= 830
96+thread 9 thri 676 Len(S)= 677
97+thread 9 thri 677 Len(S)= 678
98+thread 10 thri 830 Len(S)= 831
99+thread 10 thri 831 Len(S)= 832
100+thread 10 thri 832 Len(S)= 833
101+thread 10 thri 833 Len(S)= 834
102+thread 10 thri 834 Len(S)= 835
103+thread 10 thri 835 Len(S)= 836
104+thread 10 thri 836 Len(S)= 837
105+thread 10 thri 837 Len(S)= 838
106+thread 10 thri 838 Len(S)= 839
107+thread 10 thri 839 Len(S)= 840
108+thread 9 thri 678 Len(S)= 679
109+...
110+...
111+thread 4 thri 994 Len(S)= 995
112+thread 4 thri 995 Len(S)= 996
113+thread 4 thri 996 Len(S)= 997
114+thread 4 thri 997 Len(S)= 998
115+thread 4 thri 998 Len(S)= 999
116+thread 4 thri 999 Len(S)= 1000
117+thread 4 finished
118+10
119+
120+}
121+
122+uses
123+ {$ifdef unix}cthreads, {$endif} sysutils;
124+
125+const
126+ threadcount = 10;
127+ stringlen = 1000;
128+
129+var
130+ finished : longint;
131+
132+threadvar
133+ thri : ptrint;
134+
135+function f(p : pointer) : ptrint;
136+var
137+ s : ansistring;
138+begin
139+ Writeln('thread ',longint(p),' started');
140+ thri:=0;
141+ while (thri<stringlen) do begin
142+ s:=s+'1'; { create a delay }
143+ writeln('thread ',longint(p),' thri ',thri,' Len(S)= ',length(s));
144+ inc(thri);
145+ end;
146+ Writeln('thread ',longint(p),' finished');
147+ InterLockedIncrement(finished);
148+ f:=0;
149+end;
150+
151+var
152+ i : longint;
153+
154+Begin
155+ finished:=0;
156+ for i:=1 to threadcount do
157+ BeginThread(@f,pointer(i));
158+ while finished<threadcount do ;
159+ Writeln(finished);
160+End.
161+```
162+
163+## The TThread Class
164+
165+The following example can be found in the examples/multithreading/ directory.
166+
167+To create a multi-threaded application, the easiest way is to use the TThread Class. This class permits the creation of an additional thread (alongside the main thread) in a simple way. Normally you are required to override only 2 methods: the Create constructor, and the Execute method.
168+
169+In the constructor, you will prepare the thread to run. You will set the initial values of the variables or properties you need. The original constructor of TThread requires a parameter called Suspended. As you might expect, setting Suspended = True will prevent the thread starting automatically after the creation. If Suspended = False, the thread will start running just after the creation. If the thread is created suspended, then it will run only after the Start method is called.
170+
171+> **Note:** Method Resume is [deprecated since FPC 2.4.4](http://wiki.freepascal.org/User_Changes_2.4.4#TThread.Suspend_and_TThread.Resume_have_been_deprecated). It is replaced by Start.
172+
173+As of FPC version 2.0.1 and later, TThread.Create also has an implicit parameter for Stack Size. You can now change the default stack size of each thread you create if you need it. Deep procedure call recursions in a thread are a good example. If you don't specify the stack size parameter, a default OS stack size is used.
174+
175+In the overridden Execute method you will write the code that will run on the thread.
176+
177+The TThread class has one important property: Terminated : boolean;
178+
179+If the thread has a loop (and this is typical), the loop should be exited when Terminated is true (it is false by default). Within each pass, the value of Terminated must be checked, and if it is true then the loop should be exited as quickly as is appropriate, after any necessary cleanup. ~~Bear in mind that the Terminate method does not do anything by default: the .Execute method must explicitly implement support for it to quit its job.~~ The Terminate method only sets the Terminated property to True.
180+
181+As we explained earlier, the thread should not interact with the visible components. Updates to visible components must be made within the context of the main thread.
182+
183+To do this, a TThread method called Synchronize exists. Synchronize requires a method within the thread (that takes no parameters) as an argument. When you call that method through Synchronize(@MyMethod), the thread execution will be paused, the code of MyMethod will be called from the main thread, and then the thread execution will be resumed.
184+
185+The exact working of Synchronize depends on the platform, but basically it does this:
186+
187+- it posts a message onto the main message queue and goes to sleep
188+- eventually the main thread processes the message and calls MyMethod. This way MyMethod is called without context, that means not during a mouse down event or during paint event, but after.
189+- after the main thread executed MyMethod, it wakes the sleeping Thread and processes the next message
190+- the Thread then continues.
191+
192+There is another important property of TThread: FreeOnTerminate. If this property is true, the thread object is automatically freed when the thread execution (.Execute method) stops. Otherwise the application will need to free it manually.
193+
194+Example:
195+
196+``` pascal
197+ Type
198+ TMyThread = class(TThread)
199+ private
200+ fStatusText : string;
201+ procedure ShowStatus;
202+ protected
203+ procedure Execute; override;
204+ public
205+ Constructor Create(CreateSuspended : boolean);
206+ end;
207+ constructor TMyThread.Create(CreateSuspended : boolean);
208+ begin
209+ inherited Create(CreateSuspended);
210+ FreeOnTerminate := True;
211+ end;
212+
213+ procedure TMyThread.ShowStatus;
214+ // this method is executed by the mainthread and can therefore access all GUI elements.
215+ begin
216+ Form1.Caption := fStatusText;
217+ end;
218+
219+ procedure TMyThread.Execute;
220+ var
221+ newStatus : string;
222+ begin
223+ fStatusText := 'TMyThread Starting...';
224+ Synchronize(@Showstatus);
225+ fStatusText := 'TMyThread Running...';
226+ while (not Terminated) and ([any condition required]) do
227+ begin
228+ ...
229+ [here goes the code of the main thread loop]
230+ ...
231+ if NewStatus <> fStatusText then
232+ begin
233+ fStatusText := newStatus;
234+ Synchronize(@Showstatus);
235+ end;
236+ end;
237+ end;
238+```
239+
240+In the application:
241+
242+``` pascal
243+ var
244+ MyThread : TMyThread;
245+ begin
246+ MyThread := TMyThread.Create(True); // This way it doesn't start automatically
247+ ...
248+ [Here the code initialises anything required before the threads starts executing]
249+ ...
250+ MyThread.Start;
251+ end;
252+```
253+
254+If you want to make your application more flexible you can create an event for the thread; this way your synchronized method won't be tightly coupled with a specific form or class: you can attach listeners to the thread's event. Here is an example:
255+
256+``` pascal
257+ Type
258+ TShowStatusEvent = procedure(Status: String) of Object;
259+
260+ TMyThread = class(TThread)
261+ private
262+ fStatusText : string;
263+ FOnShowStatus: TShowStatusEvent;
264+ procedure ShowStatus;
265+ protected
266+ procedure Execute; override;
267+ public
268+ Constructor Create(CreateSuspended : boolean);
269+ property OnShowStatus: TShowStatusEvent read FOnShowStatus write FOnShowStatus;
270+ end;
271+
272+ constructor TMyThread.Create(CreateSuspended : boolean);
273+ begin
274+ inherited Create(CreateSuspended);
275+ FreeOnTerminate := True;
276+ end;
277+
278+ procedure TMyThread.ShowStatus;
279+ // this method is executed by the mainthread and can therefore access all GUI elements.
280+ begin
281+ if Assigned(FOnShowStatus) then
282+ begin
283+ FOnShowStatus(fStatusText);
284+ end;
285+ end;
286+
287+ procedure TMyThread.Execute;
288+ var
289+ newStatus : string;
290+ begin
291+ fStatusText := 'TMyThread Starting...';
292+ Synchronize(@Showstatus);
293+ fStatusText := 'TMyThread Running...';
294+ while (not Terminated) and ([any condition required]) do
295+ begin
296+ ...
297+ [here goes the code of the main thread loop]
298+ ...
299+ if NewStatus <> fStatusText then
300+ begin
301+ fStatusText := newStatus;
302+ Synchronize(@Showstatus);
303+ end;
304+ end;
305+ end;
306+```
307+
308+In the application:
309+
310+``` pascal
311+ Type
312+ TForm1 = class(TForm)
313+ Button1: TButton;
314+ Label1: TLabel;
315+ procedure FormCreate(Sender: TObject);
316+ procedure FormDestroy(Sender: TObject);
317+ private
318+ { private declarations }
319+ MyThread: TMyThread;
320+ procedure ShowStatus(Status: string);
321+ public
322+ { public declarations }
323+ end;
324+
325+ procedure TForm1.FormCreate(Sender: TObject);
326+ begin
327+ inherited;
328+ MyThread := TMyThread.Create(true);
329+ MyThread.OnShowStatus := @ShowStatus;
330+ end;
331+
332+ procedure TForm1.FormDestroy(Sender: TObject);
333+ begin
334+ MyThread.Terminate;
335+
336+ // FreeOnTerminate is true so we should not write:
337+ // MyThread.Free;
338+ inherited;
339+ end;
340+
341+ procedure TForm1.Button1Click(Sender: TObject);
342+ begin
343+ MyThread.Start;
344+ end;
345+
346+ procedure TForm1.ShowStatus(Status: string);
347+ begin
348+ Label1.Caption := Status;
349+ end;
350+```
351+
352+## Special things to take care of
353+
354+### Stack checking under Windows
355+
356+There is a potential headache in Windows with Threads if you use the -Ct (stack check) switch. For reasons not so clear the stack check will "trigger" on any TThread.Create if you use the default stack size. The only work-around for the moment is to simply not use -Ct switch. Note that it does NOT cause an exception in the main thread, but in the newly created one. This "looks" like if the thread was never started.
357+
358+A good code to check for this and other exceptions which can occur in thread creation is:
359+
360+``` pascal
361+MyThread := TThread.Create(False);
362+
363+if Assigned(MyThread.FatalException) then
364+ raise MyThread.FatalException;
365+```
366+
367+This code will assure that any exception which occurred during thread creation will be raised in your main thread.
368+
369+### GetDC function in Windows
370+
371+The GetDC (and GetDCEx) function retrieves a handle to a device context (DC) for the client area of a specified window or for the entire screen. It can be used, for example, to [[Developing with Graphics|take a screenshot]]. Note however that it is not thread safe: the handle to the DC can only be used by a single thread at any one time as [documented here](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc).
372+
373+### Multithreading in packages
374+
375+Packages which uses multi-threading should add the **-dUseCThreads** flag to the custom usage options. Open the package editor of the package, then Options \> Usage \> Custom and add *-dUseCThreads*. This will define this flag to all projects and packages using this package, including the IDE. The IDE and all new applications created by the IDE have already the following code in their .lpr file:
376+
377+``` pascal
378+uses
379+ {$IFDEF UNIX}{$IFDEF UseCThreads}
380+ cthreads,
381+ cmem, // the c memory manager is on some systems much faster for multi-threading
382+ {$ENDIF}{$ENDIF}
383+```
384+
385+### Heaptrc
386+
387+You can not use the -gh switch with the *cmem* unit. The -gh switch uses the heaptrc unit, which extends the heap manager. Therefore the **heaptrc** unit must be used **after** the **cmem** unit.
388+
389+``` pascal
390+uses
391+ {$IFDEF UNIX}{$IFDEF UseCThreads}
392+ cthreads,
393+ cmem, // the c memory manager is on some systems much faster for multi-threading
394+ {$ENDIF}{$ENDIF}
395+ heaptrc,
396+```
397+
398+### Initialization and Finalization
399+
400+To initialize the thread object itself, you can either start it suspended and set its properties and/or create a new constructor and call the inherited constructor.
401+
402+**Note**: Using the AfterConstruction when CreateSuspended=false is dangerous, as the thread has already started.
403+
404+On the other hand, the destructor may be used to finalize the object's resources.
405+
406+``` pascal
407+type
408+ TMyThread = class(TThread)
409+ private
410+ fRTLEvent: PRTLEvent;
411+ public
412+ constructor Create(SomeData: TSomeObject; CreateSuspended: boolean);
413+ destructor Destroy; override;
414+ end;
415+
416+constructor TMyThread.Create(SomeData: TSomeObject; CreateSuspended: boolean);
417+begin
418+ // example: set up events, critical sections and other ressources like files or database connections
419+ RTLEventCreate(fRTLEvent);
420+ inherited Create(CreateSuspended);
421+end;
422+
423+destructor TMyThread.Destroy;
424+begin
425+ RTLeventDestroy(fRTLEvent);
426+ inherited Destroy;
427+end;
428+```
429+
430+### Non LCL program
431+
432+TThread.Synchronize requires that the main thread regularly calls CheckSynchronize. The LCL does that in its loop. If you don't use the LCL event loop you must call it yourself.
433+
434+## SMP Support
435+
436+The good news is that if your application works properly multi-threaded this way, it is already SMP enabled!
437+
438+## Debugging Multi-threaded Applications with Lazarus
439+
440+The debugging on Lazarus requires GDB and is rapidly becoming more and more fully featured and stable. However, there still exists a few Linux distributions with some problems.
441+
442+### Debugging output
443+
444+In a single threaded application, you can simply write to console/terminal/whatever and the order of the lines is the same as they were written. In multi-threaded application things are more complicated. If two threads are writing, say a line is written by thread A before a line by thread B, then the lines are not necessarily written in that order. It can even happen, that a thread writes its output, while the other thread is writing a line.While under linux (maybe) you'll get proper [[DebugLn]]() output, under win32 you can get exceptions (probably DiskFull) because of DebugLn() usage outside of main thread.So, to avoid headaches use DebugLnThreadLog() mentioned below.
445+
446+The LCLProc unit contains several functions, to let each thread write to its own log file:
447+
448+``` pascal
449+ procedure DbgOutThreadLog(const Msg: string); overload;
450+ procedure DebuglnThreadLog(const Msg: string); overload;
451+ procedure DebuglnThreadLog(Args: array of const); overload;
452+ procedure DebuglnThreadLog; overload;
453+```
454+
455+For example: Instead of *writeln('Some text ',123);* use
456+
457+` DebuglnThreadLog(['Some text ',123]);`
458+
459+This will append a line 'Some text 123' to **Log\<PID\>.txt**, where \<PID\> is the process ID of the current thread.
460+
461+It is a good idea to remove the log files before each run:
462+
463+` rm -f Log* && ./project1`
464+
465+### Linux
466+
467+If you try to debug a multi-threaded application on Linux, you will have one big problem: the Desktop Manager on X server can hang. This happens for instance when the application has captured the mouse/keyboard and was paused by gdb and the X server waits for your application. When that happens you can simply log in from another computer and kill the gdb or exit out of that session by pressing CTRL+ALT+F3 and kill gdb. Alternatively you can restart the window manager: enter sudo /etc/init.d/gdm restart. This will restart the desktop manager and get you back into your desktop.
468+
469+Since it depends where gdb stops your program in some cases some tricks may help: for Ubuntu x64 set the Project options for debugging required extra information file...
470+
471+` Project Options -> Compiler Options -> Linking -> Debugging: Check Use external gdb debug symbols file (-Xg).`
472+
473+The other option is to open another X desktop, run the IDE/gdb on one and the application on the other, so that only the test desktop freezes. Create a new instance of X with:
474+
475+` X :1 &`
476+
477+It will open, and when you switch to another desktop (the one you are working with pressing CTRL+ALT+F7), you will be able to go back to the new graphical desktop with CTRL+ALT+F8 (if this combination does not work, try with CTRL+ALT+F2... this one worked on [Slackware](http://www.slackware.com)).
478+
479+Then you could, if you want, create a desktop session on the X started with:
480+
481+` gnome-session --display=:1 &`
482+
483+Then, in Lazarus, on the run parameters dialog for the project, check "Use display" and enter :1.
484+
485+Now the application will run on the second X server and you will be able to debug it on the first one.
486+
487+This was tested with Free Pascal 2.0 and Lazarus 0.9.10 on Windows and Linux.
488+
489+------------------------------------------------------------------------
490+
491+Instead of creating a new X session, one can use [Xnest](http://en.wikipedia.org/wiki/Xnest). Xnest is a X session on a window. Using it X server didn't lock while debugging threads, and it's much easier to debug without keeping changing terminals.
492+
493+The command line to run Xnest is
494+
495+` Xnest :1 -ac`
496+
497+to create a X session on :1, and disabling access control.
498+
499+## Lazarus Widgetset Interfaces
500+
501+The win32, the gtk and the carbon interfaces support multi-threading. This means, TThread, critical sections and Synchronize work. But they are not thread safe. This means only one thread at a time can access the LCL. And since the main thread should never wait for another thread, it means only the main thread is allowed to access the LCL, which means anything that has to do with TControl, Application and LCL widget handles. There are some thread safe functions in the LCL. For example most of the functions in the FileUtil unit are thread safe.
502+
503+### Using SendMessage/PostMessage to communicate between threads
504+
505+Only one thread in an application should call LCL APIs, usually the main thread. Other threads can make use of the LCL through a number of indirect methods, one good option being the usage of SendMessage or PostMessage. LCLIntf.SendMessage and LCLIntf.PostMessage will post a message directed to a window in the message pool of the application.
506+
507+See also the documentation for these routines:
508+
509+- [[doc:lcl/lclintf/sendmessage.html|SendMessage]]
510+- [[doc:lcl/lclintf/postmessage.html|PostMessage]]
511+
512+The difference between SendMessage and PostMessage is the way that they return control to the calling thread. Like Synchronize, SendMessage blocks and control is not returned until the window that the message was sent to has completed processing it; however under certain circumstances SendMessage might attempt to optimise processing by remaining in the context of the thread that called it. With PostMessage control is returned immediately up to some system-defined maximum number of enqueued messages and as long as space remains on the heap for attached data.
513+
514+In both cases the procedure handling the message (see below) should avoid calling application.ProcessMessages, since this might cause a second message to be dispatched which will be handled reentrantly. If this is unavoidable then it would probably be preferable to use some other mechanism to transfer serialised events between threads.
515+
516+Here is an example of how a secondary thread could send text to be displayed in an LCL control to the main thread:
517+
518+``` pascal
519+const
520+ WM_GOT_ERROR = LM_USER + 2004;
521+ WM_VERBOSE = LM_USER + 2005;
522+
523+procedure VerboseLog(Msg: string);
524+var
525+ PError: PChar;
526+begin
527+ if MessageHandler = 0 then Exit;
528+ PError := StrAlloc(Length(Msg)+1);
529+ StrCopy(PError, PChar(Msg));
530+ PostMessage(formConsole.Handle, WM_VERBOSE, Integer(PError), 0);
531+end;
532+```
533+
534+And an example of how to handle this message from a window:
535+
536+``` pascal
537+const
538+ WM_GOT_ERROR = LM_USER + 2004;
539+ WM_VERBOSE = LM_USER + 2005;
540+
541+type
542+ { TformConsole }
543+
544+ TformConsole = class(TForm)
545+ DebugList: TListView;
546+ // ...
547+ private
548+ procedure HandleDebug(var Msg: TLMessage); message WM_VERBOSE;
549+ end;
550+
551+var
552+ formConsole: TformConsole;
553+
554+implementation
555+
556+....
557+
558+{ TformConsole }
559+
560+procedure TformConsole.HandleDebug(var Msg: TLMessage);
561+var
562+ Item: TListItem;
563+ MsgStr: PChar;
564+ MsgPasStr: string;
565+begin
566+ MsgStr := PChar(Msg.wparam);
567+ MsgPasStr := StrPas(MsgStr);
568+ Item := DebugList.Items.Add;
569+ Item.Caption := TimeToStr(SysUtils.Now);
570+ Item.SubItems.Add(MsgPasStr);
571+ Item.MakeVisible(False);
572+
573+// Followed by something like
574+
575+ TrayControl.SetError(MsgPasStr);
576+ StrDispose(MsgStr)
577+end;
578+
579+end.
580+```
581+
582+When you get on the Linux x64 machine an error: "Project XY raised exception class 'External: SIGSEGV'" you have to change "Integer(PError)" to "PtrInt(PError)" in procedure "VerboseLog". Modified line have to look like:
583+
584+` PostMessage(formConsole.Handle, WM_VERBOSE, PtrInt(PError), 0);`
585+
586+## Critical sections
587+
588+A *critical section* is an object used to make sure, that some part of the code is executed only by one thread at a time. A critical section needs to be created/initialized before it can be used and be freed when it is not needed anymore.
589+
590+There are two ways you use critical sections, from the RTL or from LCL. The text below shows the RTL model and shows the LCL alternatives as a comment, the only difference is the method names.
591+
592+Critical sections are normally used this way:
593+
594+``` pascal
595+// uses LCLIntf, LCLType;
596+```
597+
598+the necessary RTL units will almost certainly already be mentioned.
599+
600+Declare the section (globally for all threads which should access the section):
601+
602+``` pascal
603+MyCriticalSection: TRTLCriticalSection;
604+// MyCriticalSection : TCriticalSection;
605+```
606+
607+Create the section:
608+
609+``` pascal
610+InitCriticalSection(MyCriticalSection);
611+//InitializeCriticalSection(MyCriticalSection);
612+```
613+
614+Run some threads. Doing something exclusively:
615+
616+``` pascal
617+EnterCriticalSection(MyCriticalSection);
618+try
619+ // access some variables, write files, send some network packets, etc
620+finally
621+ LeaveCriticalSection(MyCriticalSection);
622+end;
623+// RTL and LCL use same syntax, thats nice.
624+```
625+
626+After all threads terminated, free it:
627+
628+``` pascal
629+DoneCriticalSection(MyCriticalSection);
630+// DeleteCriticalSection(MyCriticalSection);
631+```
632+
633+As an alternative, you can use a TCriticalSection object. The creation does the initialization, the Enter method does the EnterCriticalSection, the Leave method does the LeaveCriticalSection and the destruction of the object does the deletion.
634+
635+Note that a critical section does not protect against the same thread entering the same block of code, only against different threads. For that reason it cannot be used to protect against e.g. reentry of a message handler (see the section above).
636+
637+For example: 5 threads incrementing a counter. See lazarus/examples/multithreading/criticalsectionexample1.lpi
638+
639+> **Warning:** There are two sets of the above four functions. The RTL and the LCL ones. The LCL ones are defined in the unit LCLIntf and LCLType. Both work pretty much the same. You can use both at the same time in your application, but you should not use a RTL function within an LCL Critical Section and vice versa.
640+
641+### Sharing Variables
642+
643+If some threads share a variable, that is read only, then there is nothing to worry about. Just read it. But if one or several threads changes the variable, then you must make sure, that only one thread accesses the variables at a time.
644+
645+For example: 5 threads incrementing a counter. See lazarus/examples/multithreading/criticalsectionexample1.lpi
646+
647+## Waiting for another thread
648+
649+If a thread A needs a result of another thread B, it must wait, till B has finished.
650+
651+**Important:** The main thread should never wait for another thread. Instead use Synchronize (see above).
652+
653+See for an example: lazarus/examples/multithreading/waitforexample1.lpi
654+
655+``` pascal
656+{ TThreadA }
657+
658+procedure TThreadA.Execute;
659+begin
660+ Form1.ThreadB:=TThreadB.Create(false);
661+ // create event
662+ WaitForB:=RTLEventCreate;
663+ while not Application.Terminated do begin
664+ // wait infinitely (until B wakes A)
665+ RtlEventWaitFor(WaitForB);
666+ writeln('A: ThreadB.Counter='+IntToStr(Form1.ThreadB.Counter));
667+ end;
668+end;
669+
670+{ TThreadB }
671+
672+procedure TThreadB.Execute;
673+var
674+ i: Integer;
675+begin
676+ Counter:=0;
677+ while not Application.Terminated do begin
678+ // B: Working ...
679+ Sleep(1500);
680+ inc(Counter);
681+ // wake A
682+ RtlEventSetEvent(Form1.ThreadA.WaitForB);
683+ end;
684+end;
685+```
686+
687+> **Note:** RtlEventSetEvent can be called before RtlEventWaitFor. Then RtlEventWaitFor will return immediately. Use RTLeventResetEvent to clear a flag.
688+
689+## Fork
690+
691+When forking in a multi-threaded application, be aware that any threads created and running BEFORE the fork (or fpFork) call, will NOT be running in the child process. As stated on the fork() man page, any threads that were running before the fork call, their state will be undefined.
692+
693+So be aware of any threads initializing before the call (including on the initialization section). They will NOT work.
694+
695+## Parallel procedures/loops
696+
697+A special case of multi threading is running a single procedure in parallel. See [[Parallel procedures]].
698+
699+## Distributed computing
700+
701+The next higher steps after multi threading is running the threads on multiple machines.
702+
703+- You can use one of the TCP suites like synapse, lnet or indy for communications. This gives you maximum flexibility and is mostly used for loosely connected Client / Server applications.
704+- You can use message passing libraries like [[MPICH]], which are used for HPC (High Performance Computing) on clusters.
705+
706+## External threads
707+
708+To make Free Pascal's threading system work properly, each newly created FPC thread needs to be initialized (more exactly, the exception, I/O system and threadvar system per thread needs to be initialized so threadvars and heap are working). That is fully automatically done for you if you use BeginThread (or indirectly by using the TThread class). However, if you use threads that were created without BeginThread (i.e. external threads), additional work (currently) might be required. External threads also include those that were created in external C libraries (.DLL/.so).
709+
710+Things to consider when using external threads (might not be needed in all or future compiler versions):
711+
712+- Do not use external threads at all - use FPC threads. If can you can get control over how the thread is created, create the thread by yourself by using BeginThread.
713+
714+If the calling convention doesn't fit (e.g. if your original thread function needs cdecl calling convention but BeginThread needs pascal convention, create a record, store the original required thread function in it, and call that function in your pascal thread function:
715+
716+``` pascal
717+type
718+ TCdeclThreadFunc = function (user_data:Pointer):Pointer;cdecl;
719+
720+ PCdeclThreadFuncData = ^TCdeclThreadFuncData;
721+ TCdeclThreadFuncData = record
722+ Func: TCdeclThreadFunc; //cdecl function
723+ Data: Pointer; //original data
724+ end;
725+
726+// The Pascal thread calls the cdecl function
727+function C2P_Translator(FuncData: pointer) : ptrint;
728+var
729+ ThreadData: TCdeclThreadFuncData;
730+begin
731+ ThreadData := PCdeclThreadFuncData(FuncData)^;
732+ Result := ptrint(ThreadData.Func(ThreadData.Data));
733+end;
734+
735+procedure CreatePascalThread;
736+var
737+ ThreadData: PCdeclThreadFuncData;
738+begin
739+ New(ThreadData);
740+ // this is the desired cdecl thread function
741+ ThreadData^.Func := func;
742+ ThreadData^.Data := user_data;
743+ // this creates the Pascal thread
744+ BeginThread(@C2P_Translator, ThreadData );
745+end;
746+```
747+
748+- Initialize the FPC's threading system by creating a dummy thread. If you don't create any Pascal thread in your app, the thread system won't be initialized (and thus threadvars won't work and thus heap will not work correctly).
749+
750+``` pascal
751+type
752+ tc = class(tthread)
753+ procedure execute;override;
754+ end;
755+
756+ procedure tc.execute;
757+ begin
758+ end;
759+
760+{ main program }
761+begin
762+ { initialise threading system }
763+ with tc.create(false) do
764+ begin
765+ waitfor;
766+ free;
767+ end;
768+ { ... your code follows }
769+end.
770+```
771+
772+(After the threading system is initialized, the runtime may set the system variable "IsMultiThread" to true which is used by FPC routines to perform locks here and there. You should not set this variable manually.)
773+
774+- If for some reason this doesn't work for you, try this code in your external thread function:
775+
776+``` pascal
777+function ExternalThread(param: Pointer): LongInt; stdcall;
778+var
779+ tm: TThreadManager;
780+begin
781+ GetThreadManager(tm);
782+ tm.AllocateThreadVars;
783+ InitThread(1000000); // adjust inital stack size here
784+
785+ { do something threaded here ... }
786+
787+ Result:=0;
788+end;
789+```
790+
791+### Identifying external threads
792+
793+Sometimes you even don't know if you have to deal with external threads (eg if some C library makes a [[callback]]). This can help to analyse this:
794+
795+1\. Ask the OS for the ID of the current thread at your application's start
796+
797+``` pascal
798+GetCurrentThreadID() // Windows;
799+GetThreadID() // Darwin (macOS); FreeBSD;
800+TThreadID(pthread_self) // Linux;
801+```
802+
803+2\. Ask again for the ID of the current thread inside the thread function and compare this with the result of step 1.
804+
805+### Give up some time slice
806+
807+[ThreadSwitch](https://www.freepascal.org/docs-html/rtl/system/threadswitch.html) - Note: may be ignored.
808+
809+> **Note:** Do not use the Windows trick [*Sleep(0)*](https://www.freepascal.org/docs-html/rtl/sysutils/sleep.html) as this won't work on all platforms.
810+
811+## See also
812+
813+- [[Streaming components]]
814+- [[Manager Worker Threads System]]
815+- [[Example of multi-threaded application: array of threads]]
816+- [[Parallel procedures]]
817+- [[Main Loop Hooks]]
818+- [[Asynchronous Calls]]
819+- [A forum discussion](https://forum.lazarus.freepascal.org/index.php/topic,55164.0.html) - useful background, why you should almost certainly not access LCL items from within a thread and what you can, safely access.
820+- [Mutlithreading - The Delphi way](http://nickhodges.com/MultiThreadingInDelphi/ToC.html)
821+- [Synchronizing Threads and GUI in a Delphi Application](https://www.thoughtco.com/synchronizing-threads-and-gui-delphi-application-1058159)
822+- [Introduction to thread programming in Lazarus](https://www.freepascal.org/~michael/articles/lazthread/lazthread.pdf) - handout given by Michael Van Canneyt
823+
824+---
825+*From the Free Pascal wiki, page "Multithreaded Application Tutorial", as it stood on 2024-02-28 after a change by Ernesto, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history