[fpc-devel] THREAD Programming IN FPC

Jason P Sage jasonpsage at jegas.org
Tue Jan 9 01:36:37 CET 2007


I was wondering the rule on MULTI-THREADING when trying to make something
THREAD SAFE.

I Have multiple threads running, and I MADE EACH have its OWN set of
VARIABLES - so there isn't VARIABLE Stomping from other THREADS.

The routines I CALL USUALLY have a few variables they use to keep track of
counters or stuff that is only VALID during the life of the Call. 

My Problem is sometimes THESE Variables that are local to the sub routines
are getting stomped in longer routines (That perhaps are getting task
switched).

My Question: Do I NEED to write THREAD SAFE ROUTINES in a manner so they do
NOT have any local variables? 

Example Pseudo Code - Hoping Someone can verify or deny I understand this
right.
-------------------

Type JThread= Class(TTHREAD)
  MyOwnVariable: Ansistring;
  MyOwnInteger: Integer;
  Procedure MyRoutine(var p_MyOwnVariable: ansistring);
  Procedure EXECUTE; override;
End;

Procedure JThread.EXECUTETHREAD;
Begin
  Repeat
    MyRoutine(MyOwnVariable);
  Until 1=2; 
End;

Var MYTHREAD1: JTHREAD;
Var MYTHREAD2: JTHREAD;

Procedure MyRoutine(var p_MyOwnVariable: ansistring);
Var i: integer;
Begin
  For i=0 to 100 do begin
     Write('AM I SAFE TO USE i?'+
           'DURING LIFE OF this '+
           'routine while other '+
           'threads use same routine?'+
           inttostr(i));
  end;
  
  // CHANGE Thread Class Vari Sample via reference
  p_MyOwnVariable:='Hi Mom';
end;

begin
  MYTHREAD1:=JTHREAD.Create;
  MYTHREAD1.EXECUTETHREAD;
  MYTHREAD2:=JTHREAD.Create;  
  MYTHREAD2.EXECUTETHREAD;  
  Repeat until 1=2;
End.

The Question is the local variable "i" safe all the time? Does it get its
own stack space? Or does it get stomped by multiple threads because its only
allocated in memory one time but multiple threads are calling the routine
"My Routine"

My experience has led me to the impression that local variables are
allocated on the stack. If they are, does each thread own its own stack
space? Do local variables get allocated on the THREAD's Stack? Or the main
program's?

Are AnsiStrings managed intelligently in threaded applications? Meaning - do
they have the same rules as other variables concerning multi-threaded
applications or does the memory counters or "reference counts" to chunk of
mem get hosed?

Thanx for any and all responses!

Jason P Sage


-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.16.7/619 - Release Date: 1/7/2007
6:29 PM
 




More information about the fpc-devel mailing list