Synchronization Primitives

Mutual exclusion (fast, in-process) Lock on any object (TMonitor.Enter(Obj)) + Wait/Pulse

TMultiReadExclusiveWriteSynchronizer / TLightweightMREW (11+) System.SysUtils / SyncObjs Many readers, one writer TSemaphore / TLightweightSemaphore TEvent / TLightweightEvent Very short critical sections

Atomic increment/exchange/compare-exchange AtomicIncrement / AtomicCmpExchange Intrinsic atomic operations TThreadList<T> / TThreadedQueue<T> Wait for N signals

Avoid deadlocks: consistent lock order, short critical sections, try..finally around every Enter/Leave. Prefer message passing and immutable data.

uses System.SyncObjs;

var Lock := TCriticalSection.Create;
var Counter := 0;
TParallel.For(1, 1000,
  procedure(I: Integer)
  begin
    Lock.Enter;
    try
      Inc(Counter);
    finally
      Lock.Leave;
    end;
  end);
// Or lock-free:
TInterlocked.Increment(Counter);
AtomicIncrement(Counter);

// TMonitor on any object
TMonitor.Enter(SharedList);
try
  SharedList.Add(Item);
finally
  TMonitor.Exit(SharedList);
end;

// Producer/consumer
var Queue := TThreadedQueue<string>.Create(100, INFINITE, 100);   // depth, push timeout, pop timeout
Queue.PushItem('job');
var Item: string;
if Queue.PopItem(Item) = wrSignaled then Process(Item);