ZetCode

Threads and synchronization in Pascal

last modified November 19, 2026 Free Pascal 3.2.2

A thread is a path of execution inside one process. Threads share the program's variables and heap, which makes communication cheap, but it also means that two threads can write the same variable at the same time and lose an update. This article starts with a thread that prints one line, then adds a worker that returns a result, protects a shared counter with a critical section, coordinates threads with an event, and sums an array in parallel.

The cthreads unit

On Unix, the thread manager is not linked automatically. A program that uses TThread must name cthreads first in its uses clause, before Classes and SysUtils. Without it the program stops with runtime error 232, "This binary has no thread support compiled in". With cthreads after Classes the first thread fails with runtime error 211, "Threading has been used before cthreads was initialized". The order is not cosmetic; it decides when the thread manager is installed.

A first worker thread

The TThread class wraps a native thread. A descendant overrides Execute, the method that runs in the new thread, and the main program calls Start and WaitFor. The smallest useful program does nothing in Execute but print one line.

hello.pas
program hello;
{$mode objfpc}{$H+}

uses
  cthreads, Classes;

type
  TGreeter = class(TThread)
  protected
    procedure Execute; override;
  end;

procedure TGreeter.Execute;
begin
  WriteLn('hello from the worker');
end;

var
  T: TGreeter;

begin
  T := TGreeter.Create(True);
  T.Start;
  T.WaitFor;
  T.Free;
  WriteLn('main thread done');
end.

Create(True) creates the object suspended, and Start begins execution. WaitFor blocks the main thread until the worker has finished, so the worker's line is printed before main thread done. The thread object is freed only after WaitFor returns, which is the safe order.

$ fpc -gl hello.pas
$ ./hello
hello from the worker
main thread done

Returning a result

The next worker does real work: it sums the integers from 1 to one million and stores the result in a field. The main program starts it, waits until it finishes, and reads the field. WaitFor guarantees that the thread has stopped before Result is read, so no lock is needed for a value that is written once and read afterwards.

simplethread.pas
program simplethread;
{$mode objfpc}{$H+}

uses
  cthreads, Classes, SysUtils;

type
  TWorker = class(TThread)
  private
    FResult: Int64;
  protected
    procedure Execute; override;
  public
    property Result: Int64 read FResult;
  end;

procedure TWorker.Execute;
var
  I: Integer;
begin
  FResult := 0;
  for I := 1 to 1000000 do
    FResult := FResult + I;
end;

var
  W: TWorker;

begin
  W := TWorker.Create(True);
  try
    W.Start;
    W.WaitFor;
    WriteLn('sum: ', W.Result);
  finally
    W.Free;
  end;
end.

Create(True) calls the inherited constructor with CreateSuspended = True; Start then begins execution. Setting FreeOnTerminate would let the thread free itself, but then the main program must not touch the reference again, not even to call WaitFor. The property exposes the result read-only, so the main thread cannot overwrite it by accident.

$ fpc -gl simplethread.pas
$ ./simplethread
sum: 500000500000

Shared counters and critical sections

The expression Count := Count + 1 is not atomic: it reads the variable, adds one, and writes the result back. If two threads interleave those three steps, one increment is lost. A critical section allows only one thread at a time to execute the protected block. The next program has two threads, each incrementing the same counter 200,000 times.

counter.pas
program counter;
{$mode objfpc}{$H+}

uses
  cthreads, Classes, SysUtils, SyncObjs;

type
  TAdder = class(TThread)
  private
    FLock: TCriticalSection;
    FCount: PInteger;
  protected
    procedure Execute; override;
  public
    constructor Create(ALock: TCriticalSection; ACount: PInteger);
  end;

constructor TAdder.Create(ALock: TCriticalSection; ACount: PInteger);
begin
  inherited Create(True);
  FLock := ALock;
  FCount := ACount;
end;

procedure TAdder.Execute;
var
  I: Integer;
begin
  for I := 1 to 200000 do
  begin
    FLock.Acquire;
    try
      FCount^ := FCount^ + 1;
    finally
      FLock.Release;
    end;
  end;
end;

var
  Lock: TCriticalSection;
  Count: Integer;
  A, B: TAdder;

begin
  Count := 0;
  Lock := TCriticalSection.Create;
  A := TAdder.Create(Lock, @Count);
  B := TAdder.Create(Lock, @Count);
  try
    A.Start;
    B.Start;
    A.WaitFor;
    B.WaitFor;
    WriteLn('count: ', Count);
  finally
    A.Free;
    B.Free;
    Lock.Free;
  end;
end.

Both workers receive the same lock and the address of the same counter. Acquire blocks while the other thread holds the lock, and Release is in a finally block so the lock is returned even if the arithmetic raises an exception. The result is exactly 400,000 on every run; without the lock it is usually smaller and never predictable.

$ fpc -gl counter.pas
$ ./counter
count: 400000

Waiting for an event

A critical section protects data, but sometimes one thread must simply wait until another has finished a step. A TEvent is a flag that a thread can wait on. With ManualReset = True the flag stays set until ResetEvent clears it; with False it resets automatically after one waiting thread is released.

eventdemo.pas
program eventdemo;
{$mode objfpc}{$H+}

uses
  cthreads, Classes, SysUtils, SyncObjs;

type
  TSignaller = class(TThread)
  private
    FEvent: TEvent;
  protected
    procedure Execute; override;
  public
    constructor Create(AEvent: TEvent);
  end;

constructor TSignaller.Create(AEvent: TEvent);
begin
  inherited Create(True);
  FEvent := AEvent;
end;

procedure TSignaller.Execute;
begin
  Sleep(100);
  WriteLn('worker: setting the event');
  FEvent.SetEvent;
end;

var
  Ev: TEvent;
  T: TSignaller;

begin
  Ev := TEvent.Create(nil, True, False, '');
  T := TSignaller.Create(Ev);
  try
    T.Start;
    WriteLn('main: waiting');
    Flush(Output);
    Ev.WaitFor(INFINITE);
    WriteLn('main: event received');
    T.WaitFor;
  finally
    T.Free;
    Ev.Free;
  end;
end.

The worker sleeps for 100 milliseconds to make the wait visible. The main thread prints its line, flushes the output buffer, and blocks in WaitFor(INFINITE) until the event is set. Flush(Output) matters here: when stdout is a pipe, Pascal buffers the text, and without the flush the two lines can appear in the opposite order. The event object is created with no owner, so the program frees it explicitly.

$ fpc -gl eventdemo.pas
$ ./eventdemo
main: waiting
worker: setting the event
main: event received

A parallel sum

Threads pay off when independent chunks of work can run at the same time. The next program fills an array of one million integers and splits it into four ranges. Each thread sums its range into its own field, and the main program adds the four partial sums after all threads have finished. No lock is needed because the threads never write the same location.

parsum.pas
program parsum;
{$mode objfpc}{$H+}

uses
  cthreads, Classes, SysUtils;

const
  N = 1000000;
  THREADS = 4;

type
  TSumPart = class(TThread)
  private
    FFirst, FLast: Integer;
    FSum: Int64;
  protected
    procedure Execute; override;
  public
    constructor Create(AFirst, ALast: Integer);
    property Sum: Int64 read FSum;
  end;

var
  Values: array of Integer;

constructor TSumPart.Create(AFirst, ALast: Integer);
begin
  inherited Create(True);
  FFirst := AFirst;
  FLast := ALast;
end;

procedure TSumPart.Execute;
var
  I: Integer;
begin
  FSum := 0;
  for I := FFirst to FLast do
    FSum := FSum + Values[I];
end;

var
  Parts: array[0..THREADS - 1] of TSumPart;
  I, Chunk: Integer;
  Total: Int64;

begin
  SetLength(Values, N);
  for I := 0 to N - 1 do
    Values[I] := 1;

  Chunk := N div THREADS;
  for I := 0 to THREADS - 1 do
    Parts[I] := TSumPart.Create(I * Chunk, (I + 1) * Chunk - 1);
  try
    for I := 0 to THREADS - 1 do
      Parts[I].Start;
    Total := 0;
    for I := 0 to THREADS - 1 do
    begin
      Parts[I].WaitFor;
      Total := Total + Parts[I].Sum;
    end;
    WriteLn('sum: ', Total);
  finally
    for I := 0 to THREADS - 1 do
      Parts[I].Free;
  end;
end.

Each range is disjoint, and the array is filled before any thread starts, so reads need no synchronization. The partial sums are collected only after WaitFor, which is the join point of the computation. On a machine with fewer cores the program still produces the same result; the threads simply take turns.

$ fpc -gl parsum.pas
$ ./parsum
sum: 1000000

Communicating with the main thread

A worker thread must not update the user interface directly, and it should not write to shared objects without protection. TThread.Synchronize runs a method in the main thread and waits for it to finish, while Queue schedules it and returns immediately. Both are appropriate for progress messages and for code that must touch the main thread's data. Synchronize must not be called from the main thread itself, or the program deadlocks.

An unhandled exception in Execute terminates the thread and is stored in FatalException; the main program can re-raise it after WaitFor. Exceptions that cross thread boundaries should be converted to data, such as an error code or a message, and handled by the thread that owns the result.

Source

Free Pascal: TThread

Free Pascal: TCriticalSection

Free Pascal: TEvent

In this article we started a minimal TThread descendant, returned a result from a worker, protected a shared counter with TCriticalSection, synchronized two threads with TEvent, and computed a parallel sum. The memory management article explains what each thread owns, and the command-line arguments article shows how a program receives its input.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.