[fpc-pascal] Strange issue with threads
    Luca Olivetti 
    luca at ventoso.org
       
    Fri May 22 17:03:23 CEST 2009
    
    
  
While I was testing an unrelated issue, I discovered this: under
windows, with fpc 2.2.4, I try to start 10000 thread (I know it's absurd
but it's just a test) and have all of them linger around for 10 seconds.
The thread actually started are 121. The problem is that no exception is
raised, so how can I be sure that a thread is really started in a more
normal scenario? Is there a hard limit on the number of threads under
windows? If so, why no exception when I try to create more?
If I run the same program under Linux, an "EThread: failed to create new
thread" exception is raised after around 300 threads.
This is the test program
---------------8<-----------8<-------------8<------------------
program project1;
{$mode objfpc}{$H+}
uses
   {$IFDEF UNIX}{$IFDEF UseCThreads}
   cthreads,
   {$ENDIF}{$ENDIF}
   Classes, Sysutils, SyncObjs
   { you can add units after this };
var
   Started:integer;
   AccessStarted:TCriticalSection;
type
   { TMyThread }
   TMyThread = class(TThread)
     procedure Execute;override;
   end;
procedure TMyThread.Execute;
begin
   AccessStarted.Acquire;
   Started:=Started+1;
   AccessStarted.Release;
   Sleep(10000);
end;
var i:integer;
{$IFDEF WINDOWS}{$R project1.rc}{$ENDIF}
begin
   AccessStarted:=TCriticalSection.Create;
   Started:=0;
   for i:=1 to 10000 do
   begin
     TMyThread.Create(false);
     writeln(i);
   end;
   while true do
   begin
     AccessStarted.Acquire;
     writeln('Threads started:',started);
     AccessStarted.Release;
     Sleep(1000);
   end;
end.
---------------8<-----------8<-------------8<------------------
If I remove the sleep(10000) (the writeln(i) should also be removed), 
the number of threads started is a random
number, normally less than the 10000 expected, hence my deduction that
there's a hard limit on the number of threads (i.e. less threads hanging
around so more can be actually started).
Bye
-- 
Luca
    
    
More information about the fpc-pascal
mailing list