[fpc-pascal] Re: question about FPC heap and threading

sethdgrover at gmail.com sethdgrover at gmail.com
Thu Aug 12 00:23:52 CEST 2010


Jonas, thank you for your response.

I actually think I have discovered my problem: I use "BeginThread" but I do  
not use "EndThread". I was under the impression that was optional, but from  
reading some other threads and issues in mantis I can see that failing to  
call EndThread (ie., just letting the function exit) can orphan the thread  
handle, at least on linux.

To illustrate:

----------------------------------------------------------------------
program Project1;

{$mode objfpc}{$H+}

uses
cthreads,
Classes,
SysUtils,
DateUtils;

{$R *.res}


var
finished : longint;

function threadFunc (p : pointer) : ptrint;
var
someMem : pointer;
begin
Writeln('thread ', longint(p), ' started');
someMem := GetMem(1024*1024);
sleep(100);
FreeMem(someMem);
someMem := nil;
Writeln('thread ', longint(p), ' finished');
InterLockedIncrement(finished);
result := 0;
// EndThread;
end;

var
i : longint;
secondsToRun : integer;
startTime : TDateTime;
begin
finished:=0;
secondsToRun := StrToIntDef(ParamStr(1), 20);
startTime := now;
i := 0;
while(SecondsBetween(now, startTime) < secondsToRun) do begin
BeginThread(@threadFunc, pointer(i));
inc(i);
sleep(50);
end;
while (finished < i) do begin
// do nothing
end;
Writeln(finished);
end.
----------------------------------------------------------------------

Running that program causes the memory reported by "top" to skyrocket.  
However, if I uncomment the "EndThread" line, memory doesn't go up at all.  
So basically I just need to go around to any of the functions I pass in to  
be run by BeginThread and make sure they all explicitly call EndThread.

Thanks!

-SG
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20100811/34f1de47/attachment.html>


More information about the fpc-pascal mailing list