Skip to content
Adam
Language

Concurrency

Tasks, parallel loops, locks and atomics.

Examples: res\examples\language\concurrency holds small, commented programs for this page's features, each listing the output it prints; run one with adam build <file> -r.

Tasks

async starts a call on a thread of its own and gives a task T; await waits for it and gives the call's result. An exception the call raised is raised again by await.

concurrency_async.adam
module exe concurrency_async;

// 1 + 2 + .. + ACount
func Sum(const ACount: int64): int64;
var
  LI: int64;
  LTotal: int64;
begin
  LTotal := 0;
  for LI := 1 to ACount do
    LTotal := LTotal + LI;
  end;
  return LTotal;
end;

var
  GSmall: task int64;
  GLarge: task int64;

begin
  GSmall := async Sum(10);
  GLarge := async Sum(1000);
  println("{} and {}", await GSmall, await GLarge);
end.
output on x86_64-windows-gnu and x86_64-linux-gnu
55 and 500500

async of a routine with no result gives a plain task, and await of it is a statement. async begin .. end runs a block on a thread of its own, reading copies of its routine's variables. cancel(T) asks a task's call to stop and cancelled() reads the request inside it: nothing is killed. The program waits for every running task before it ends.

Parallel loops

for parallel I := A to B do .. end; runs its body once per value of I, spread over the processors; the loop declares I itself. In the body, workerindex() is the worker running the pass and workercount() the loop's workers. A write two workers share needs a lock or an atomic such as atomicadd:

readme_first_look.adam
module exe readme_first_look;

// The square of AValue, run as a task
func Square(const AValue: int64): int64;
begin
  return AValue * AValue;
end;

var
  LTask: task int64;
  LSum: int64;

begin
  LTask := async Square(12);
  LSum := 0;
  for parallel I := 1 to 100 do
    atomicadd(LSum, I);
  end;
  println("square {}", await LTask);
  println("sum {}", LSum);
end.
output on x86_64-windows-gnu and x86_64-linux-gnu
square 144
sum 5050

Locks

mutex is a lock that starts unlocked. lock (M) do .. end; holds it while its statements run and lets it go on every way out, and trylock takes it only when it can.

concurrency_lock.adam
module exe concurrency_lock;

var
  GCount: int64;
  GGuard: mutex;

// Adds one to GCount AHits times, each under the lock
func Hit(const AHits: int64);
var
  LI: int64;
begin
  for LI := 1 to AHits do
    lock (GGuard) do
      GCount := GCount + 1;
    end;
  end;
end;

var
  GOne: task;
  GTwo: task;

begin
  GOne := async Hit(1000);
  GTwo := async Hit(1000);
  await GOne;
  await GTwo;
  println("count {}", GCount);
end.
output on x86_64-windows-gnu and x86_64-linux-gnu
count 2000

Atomics

atomicadd, atomicswap, atomiccas, atomicload and atomicstore act on an int32, int64, uint32, uint64 or ptr shared between threads, every thread seeing their effects in one order.

↑ ↓ moveEnter openEsc close