A US Letter page rasterised at 300 DPI is 2,550 by 3,300 pixels, and budgeted at four bytes per pixel that comes to 33,660,000 bytes for a single page. Collect the results of a 10,000-page manual into a list and the export needs about 336 GB of bitmaps before it has written one file to disk. Adding threads does not change that total at all; it only reaches the wall sooner, because the sum of live bitmaps runs out long before CPU time does
What keeps the footprint flat is a hard bound on how many finished pages may exist at once, plus a consumer that drains them in page order so the bound can stay small. That moves the API from "give me an array" to "call me once per page"
Array results versus ordered callbacks in HotPDF
HotPDF offers both shapes. RenderLoadedPagesParallel(PageIndices, DPI, MaxConcurrency, Bitmaps) fills a THPDFBitmapArray that the caller owns and frees. RenderLoadedPagesParallelOrdered(PageIndices, DPI, MaxConcurrency, OutputQueueDepth, Callback) hands each page to a THPDFParallelRenderPageEvent in input order and frees the bitmap when the callback returns. Each has an overload with a trailing out Info: THPDFParallelRenderPipelineInfo for statistics
Both entry points normalise their arguments the same way. A MaxConcurrency below 1 means one worker per logical processor (TThread.ProcessorCount), capped at 64 and at the number of pages requested. A DPI below 1 becomes 150. Any page index outside the loaded document raises ERangeError before a single thread starts. In the ordered form, an OutputQueueDepth below 1 becomes the worker count, and the function returns the number of pages actually delivered to the callback
The array form is fine for a contact sheet of twelve thumbnails, where you need all of them on screen together anyway. Anything whose page count you do not control — whole-document export, a print spool, a hashing or OCR pass — belongs on the ordered form. A user will eventually feed it a 4,000-page scan
Why does a page render in two stages?
Rendering one page is really two jobs. The content stream is first parsed and compiled into a display list: operators tokenised, resources resolved, drawing commands recorded. The display list is then played back into a bitmap. Compilation touches the document's shared display-list cache, while playback is where the pixel memory gets allocated, so the two stages want different kinds of coordination
HotPDF keeps the cache lock narrow. It protects the bookkeeping only — recency order, use counts and the admission decision — and the compile itself runs outside it. When a worker finishes compiling, it checks the cache again; if another worker published the same page in the meantime, the fresh copy is freed and the cached entry is used instead. Two workers can therefore occasionally compile the same page at once. That costs a little CPU, and it is the right price: holding the lock across compilation would queue every page of the document behind one critical section, and in a multi-page export distinct pages are the normal case
Because the stages are decoupled, a worker that has compiled page 0 starts playback immediately while the others are still compiling. CompiledPagesAtFirstResult in the statistics records how many pages had been compiled at the moment the first bitmap was finished. A value close to PageCount means the run behaved like a compile barrier after all, which usually points at one very expensive page at the front of the list
Ordered delivery and backpressure in RenderLoadedPagesParallelOrdered
Workers finish in whatever order they finish. Each completed bitmap is parked in an output slot addressed by its input position, and a consumer loop on the calling thread delivers only the page whose turn it is. The callback is never entered concurrently, so it can write to a single file or encoder without locks
The bound comes from where the slot is taken. A worker must reserve an output slot before it starts rasterising, and the count it is checked against includes pages waiting for delivery, the page currently inside your callback and pages still being rasterised. With OutputQueueDepth set to 2, no more than two page bitmaps exist at any moment, whatever the document length
One slot is also held back for the head of the line. The page due next may take any free slot; every later page may use at most OutputQueueDepth - 1 slots and must lie within OutputQueueDepth positions of the delivery point. Picture what happens without that rule at depth 2: page 0 is a dense engineering drawing, pages 1 and 2 are plain text, so they finish first and fill both slots. Page 0 is compiled but cannot get a slot to rasterise into, and the consumer waits for page 0 forever. Every thread sits idle at 0% CPU — the signature of that particular hang
The main flow for a batch export looks like this. The callback must be a method, since THPDFParallelRenderPageEvent is declared of object
uses
System.SysUtils, Vcl.Graphics, HPDFDoc;
procedure TExportJob.PageReady(Sender: TObject; InputIndex,
PageIndex: Integer; Bitmap: TBitmap; var Cancel: boolean);
begin
// Bitmap is borrowed: the pipeline frees it as soon as this method returns
Bitmap.SaveToFile(Format('%s\page-%.5d.bmp', [FOutDir, PageIndex + 1]));
Cancel := FUserCancelled;
end;
procedure TExportJob.Run(const FileName: string);
var
Pdf: THotPDF;
Pages: array of Integer;
Info: THPDFParallelRenderPipelineInfo;
I, Delivered: Integer;
begin
Pdf := THotPDF.Create(nil);
try
if Pdf.LoadFromFile(FileName) <= 0 then
Exit;
SetLength(Pages, Pdf.LoadedPageCount);
for I := 0 to High(Pages) do
Pages[I] := I;
// MaxConcurrency 0 = one worker per logical processor,
// OutputQueueDepth 0 = one output slot per worker
Delivered := Pdf.RenderLoadedPagesParallelOrdered(Pages, 300, 0, 0,
PageReady, Info);
FLog.Add(Format('%d of %d pages, %d workers, %d ms',
[Delivered, Info.PageCount, Info.WorkerCount, Info.TotalMilliseconds]));
finally
Pdf.Free;
end;
end;
Notice the two zeros. Depth and raster concurrency are coupled: a page being rasterised already occupies a slot, so eight workers with OutputQueueDepth 2 rasterise at most two pages at a time, and the other six compile one page each and then wait. BackpressureWaitCount climbs even when the callback is fast. Start with depth equal to the worker count. Lower it only when one bitmap per worker does not fit in memory, and reduce the worker count with it, since surplus workers can only compile ahead
The consumer loop runs on whichever thread made the call, and that thread blocks until the last page is delivered. Called from the VCL main thread, the form stops repainting for the length of the export. Run the job on a background TThread and push progress to the UI with TThread.Queue from inside the callback
How many workers does the memory budget allow?
Before any thread starts, HotPDF estimates a memory reservation for every requested page: the page size at the requested DPI times four bytes, plus a working allowance of twice LoadedStreamMemoryThreshold (16 MiB by default, so 32 MiB). The largest estimate in the request is divided into the currently free part of PeakMemorySchedulerBudgetBytes, which defaults to 512 MiB, and the worker count is clamped to that quotient. At least one worker always survives
Suppose the document is all US Letter at 300 DPI. Each page reserves 33,660,000 + 33,554,432 = 67,214,432 bytes, and 536,870,912 divided by that is 7.99, so a request for eight workers runs with seven. The same pages at 600 DPI reserve 168,194,432 bytes each and get three workers. A page whose estimate exceeds the entire budget is still admitted, but only when no other reservation is outstanding, so it renders alone
The budget is process-wide. The scheduler behind PeakMemorySchedulerBudgetBytes is shared by every THotPDF instance in the process, so setting the property on one document changes it for all of them, and two exports running side by side divide it between them. A budget of 0 removes the limit, and PeakMemorySchedulerEnabled := False takes one document out of scheduling. Leave both alone for batch work: switching the scheduler off brings back exactly the crash from the first paragraph
Each worker takes its reservation after claiming a page and before compiling, and it covers compilation and playback together. Reserving only around rasterisation would miss the display list and the parser's working set, which on graphics-heavy pages can outweigh the bitmap. Workers that cannot be admitted queue in arrival order. The two APIs then part ways: the array form releases a reservation as soon as its bitmap is complete, because the bitmap now belongs to you and the scheduler can no longer track it, while the ordered form moves the reservation into the output slot with the bitmap and frees it only after your callback returns
The scheduler's own counters show what the budget did on your documents
uses
System.SysUtils, HPDFDoc, HPDFCache;
procedure TExportJob.RunHighRes(Pdf: THotPDF; const Pages: array of Integer);
var
Info: THPDFParallelRenderPipelineInfo;
Stats: THPDFPeakMemorySchedulerStatistics;
begin
// Process-wide setting: every THotPDF instance shares this budget
Pdf.PeakMemorySchedulerBudgetBytes := Int64(1024) * 1024 * 1024;
Pdf.ResetPeakMemorySchedulerStatistics;
Pdf.RenderLoadedPagesParallelOrdered(Pages, 600, 0, 0, PageReady, Info);
// MemoryBudgetWorkerLimit stays 0 when the budget was not consulted
if Info.MemoryBudgetWorkerLimit > 0 then
FLog.Add(Format('budget allowed %d of %d workers, largest page %d bytes',
[Info.MemoryBudgetWorkerLimit, Info.RequestedWorkerCount,
Info.PeakPageReservationBytes]));
if Pdf.GetPeakMemorySchedulerStatistics(Stats) then
FLog.Add(Format('peak reserved %d bytes, delayed admissions %d',
[Stats.PeakReservedBytes, Stats.DelayedAdmissionCount]));
end;
Cancellation, callback exceptions and the bitmap you must not keep
Setting Cancel to True in the callback stops workers from claiming new pages and wakes any worker waiting for an output slot or a memory reservation. Pages already being compiled or rasterised finish their current stage and are discarded. The call then returns the number of pages delivered so far, without raising, and Info.Cancelled is True
An exception raised inside the callback is treated differently. The consumer catches it, records it as the run's failure, lets the workers drain, and re-raises only after every worker has joined, as a plain Exception whose message starts with Ordered parallel page rendering failed: Ordered render callback failed: followed by the original class name and message. Only the first failure is kept. A disk-full error from SaveToFile therefore surfaces once, after the threads are gone
The shutdown order matters more than it looks. Cancellation state is set first, the reservations held by undelivered bitmaps are released second, and the workers are joined last. Swap the last two and you get a closed loop: a worker waits for memory that is held by bitmaps nobody will consume, while the caller waits for that same worker to exit
The common mistake on the caller's side is keeping the bitmap. Storing the reference looks harmless and compiles cleanly, but the pipeline frees that object the moment the callback returns
// Wrong: FPages ends up holding objects the pipeline has already freed
procedure TThumbJob.PageReadyWrong(Sender: TObject; InputIndex,
PageIndex: Integer; Bitmap: TBitmap; var Cancel: boolean);
begin
FPages.Add(Bitmap);
end;
// Right: take your own copy; FPages is a TObjectList<TBitmap>
// created with OwnsObjects = True
procedure TThumbJob.PageReady(Sender: TObject; InputIndex,
PageIndex: Integer; Bitmap: TBitmap; var Cancel: boolean);
var
Owned: TBitmap;
begin
Owned := TBitmap.Create;
try
Owned.Assign(Bitmap);
FPages.Add(Owned);
except
Owned.Free;
raise;
end;
end;
Copying every page puts you back where the array form started: those copies are your memory, outside the budget's view. Copy only what you need beyond the callback, such as a downscaled thumbnail, and let the full-resolution bitmap go
Interactive viewers have a related concern. Single-page calls such as RenderLoadedPageToBitmap cancel any running PrefetchLoadedPages work before they render, so the page a user is waiting for never queues behind background prefetching. Cancellation is checked inside the library's own parsing and rendering loops; a single call into an image codec or the operating system runs to completion before the next check. The queue-based pattern for viewers is covered in background rendering with a request queue
Reading THPDFParallelRenderPipelineInfo after a run
THPDFParallelRenderPipelineInfo separates numbers that are easy to confuse. RequestedWorkerCount is the count after the processor and page-count caps, WorkerCount is what actually ran, and MemoryBudgetWorkerLimit shows whether the budget made the difference. CompiledPageCount against CacheHitPageCount shows how much the display-list cache saved, and PeakConcurrentRenderStages never exceeds OutputQueueDepth
Two fields drive most tuning decisions:
BackpressureWaitCounthigh: the callback is the bottleneck, or the depth is smaller than the worker count. Speed up the callback first, then raise the depth if memory allowsMemorySchedulerWaitMillisecondsorMemorySchedulerDelayedPageCounthigh: the budget is the bottleneck. Lower the DPI, raise the budget, or accept fewer workers
In neither case does asking for more workers help; the extra threads just add to the wait counters. A reasonable first run uses 0 for both concurrency and depth, and a DPI taken from the real output requirement — a 150 DPI preview has no use for 300 DPI pages. Run it once on a representative document, read the statistics, and adjust one parameter at a time. When the source PDF is itself too large to hold comfortably in memory, pair this with the direct file API for large PDF workflows
The parallel pipeline, the display-list cache and page prefetching ship together in the HotPDF rendering engine for Delphi and C++Builder; licensing, editions and the full rendering feature set are listed on the HotPDF Delphi PDF component page