I have some strange issue using a library function within a thread. Please have a look at the following minimal example codes:
library library1;
{$mode objfpc}{$H+}
uses
cthreads;
procedure test (var result: integer); stdcall;
begin
result:=42;
end;
exports
test;
begin
end.
program project1;
uses
cthreads,
classes,
dynlibs;
type
ttestproc = procedure (var result: integer); stdcall;
tmythread = class(tthread)
procedure execute; override;
protected
h: tlibhandle;
f: ttestproc;
end;
procedure tmythread.execute;
var i: integer;
begin
h := loadlibrary ('./liblibrary1.so');
f := ttestproc (getprocedureaddress (h, 'test'));
f(i);
unloadlibrary(h);
end;
var
t: tmythread;
h1: tlibhandle;
begin
h1 := loadlibrary ('./liblibrary1.so');
t := tmythread.create(true);
t.start;
t.waitfor;
unloadlibrary (h1);
end.
I have a library which has to be held in memory; therefore it's initialized in the main thread and released only when the main thread finishes. Functions within the library have to be called within child threads. The code works well on Windows32 and on Linux64.
However, on Linux32, with the "Stack Overflow checking" activated when compiling the library, a Stack Overflow Error 202 occurs in the call of the library function in line 22 of the main program. Note that this problem only arises when
a) The library has already been loaded before (line 31), and
b) when it's executed within a thread. Replace t.start in line 33 with t.execute, and everything is fine.
It would be kind if someone could tell me whether I have made a mistake in programming or if this problem is du a compiler bug.
Tested on Ubuntu 15.10, Lazarus 1.4, FPC 2.6.4.