[fpc-devel] calls to Fpc-made library from C not thread-safe

Dominique Leducq dleducq at magellan-ing.fr
Thu Nov 30 15:56:06 CET 2006


On Thu, 30 Nov 2006 16:43:28 +0200
"Vlad" <vlad_mail_ru at mail.ru> wrote:

> 
> > Hi,
> > 
> > I have a library compiled with Fpc, used from C/C++ programs.
> > When these C programs call functions of the library from different threads, things break.
> > 
> > As I understand it, the exception stack(s), the standard input/output streams, the threadID and stack checking variables use thread variables, and when the thread is created from C, this variables are not allocated nor initialized.
> > 
> > As a workaround, I thought I could export a function from the library, to be called in each thread before any other library call, which would call CurrentTM.AllocateThreadVars and System.InitThread.
> > And symetrically, a function to be called after any other library call in the thread, which flushes the input/output streams and calls CurrentTM.ReleaseThreadVars.
> > 
> > Does that sound correct?
> > 
> > Dominique
> > 
> 
> Hi
> 
> I'm in similar situation under Mac OS X.
> I have to create dummy thread when library loaded and then to use such functions in additional threads:
> 
> procedure thread_init;
> var
>   TM: TThreadManager;
> begin
>   GetThreadManager(TM);
>   TM.AllocateThreadVars;
>   InitThread(500000); // 500000 is the stack size, all threads have 512Kb stack, not sure must here be exact stack size or not.
> end;
> 
> procedure thread_done;
> var
>   TM: TThreadManager;
> begin
>   GetThreadManager(TM);
>   TM.ReleaseThreadVars;
> end;
> 

Thanks Vlad, that's precisely what I was going to try out (whithout AllocateThreadVars, not needed any more after the fix of Michael).
In thread_done, I'll add 

  Flush(Output);
  Flush(ErrOutput);
  Flush(StdOut);
  Flush(StdErr);  

too (before releasing the thread variables, of course).

Dominique.




More information about the fpc-devel mailing list