Recent

Author Topic: Calling library within TThread  (Read 2260 times)

piola

  • Full Member
  • ***
  • Posts: 124
  • Lazarus 2.2, 64bit on Windows 8.1 x64
Calling library within TThread
« on: December 30, 2015, 12:18:20 pm »
I have some strange issue using a library function within a thread. Please have a look at the following minimal example codes:

Code: Text  [Select][+][-]
  1. library library1;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. uses
  6.   cthreads;
  7.  
  8. procedure test (var result: integer); stdcall;
  9. begin
  10.   result:=42;
  11. end;
  12.  
  13. exports
  14.   test;
  15.  
  16. begin
  17. end.
  18.  

Code: Text  [Select][+][-]
  1. program project1;
  2.  
  3. uses
  4.   cthreads,
  5.   classes,
  6.   dynlibs;
  7.  
  8. type
  9.   ttestproc = procedure (var result: integer); stdcall;
  10.   tmythread = class(tthread)
  11.     procedure execute; override;
  12.     protected
  13.     h: tlibhandle;
  14.     f: ttestproc;
  15.   end;
  16.  
  17. procedure tmythread.execute;
  18. var i: integer;
  19. begin
  20.   h := loadlibrary ('./liblibrary1.so');
  21.   f := ttestproc (getprocedureaddress (h, 'test'));
  22.   f(i);
  23.   unloadlibrary(h);
  24. end;
  25.  
  26. var
  27.   t:  tmythread;
  28.   h1: tlibhandle;
  29.  
  30. begin
  31.   h1 := loadlibrary ('./liblibrary1.so');
  32.   t := tmythread.create(true);
  33.   t.start;
  34.   t.waitfor;
  35.   unloadlibrary (h1);
  36. end.
  37.  

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.

 

TinyPortal © 2005-2018