Skip to content
ffredyk edited this page Jul 23, 2026 · 1 revision

add

Category

Shared (Atomic) / Arithmetic

Arity

Binary<shared|number> add <number>.

<shared> add <number>     // atomic increment
<number> add <number>     // regular addition

Description

Dual-purpose addition command:

  • On Shared variable: performs an atomic increment. Thread-safe from any scheduler. Returns the new value.
  • On regular number: performs standard addition (same as +). Returns the sum.

Auto-unwraps shared values when used on regular numbers.

How It Works

  • Shared: uses Interlocked.Add (or equivalent CAS loop) for atomic increment. The operation is indivisible — no other fiber can see a partial state.
  • Number: delegates to the standard + implementation.

Usage

Atomic counter

shared _counter = 0;
_counter add 1;                // atomic — safe from any fiber
_counter add 5;                // atomic add 5

Multi-scheduler counting

shared _kills = 0;
// Called from any scheduler:
_kills add 1;                  // thread-safe kill counter

Regular number addition (not atomic)

_result = 3 add 4;             // 7 (same as 3 + 4)
_x = _x add 1;                 // increment (not atomic for regular vars)

Atomic accumulator

shared _totalDamage = 0;
// Multiple fibers add damage:
_totalDamage add _incomingDamage;
// Later:
_damageSum = get _totalDamage;

vs + operator

shared _counter = 0;
_counter add 1;                // ATOMIC — correct
_counter = get _counter + 1;   // NOT atomic — race condition!

Always use add (or compareSwap) for shared variable modification. Never use get + arithmetic + set — it creates a race condition.

Thread Safety

  • On Shared: Fully atomic. Thread-safe from any scheduler.
  • On Number: Standard computation. Thread-safe for value types.

See Also

  • sub — atomic subtract
  • get — atomic read
  • set — write (not atomic on shared)
  • compareSwap — atomic CAS
  • + — standard addition

SQ# Wiki

Home

Engine Docs

Migration

Commands

Value Constructors

Arithmetic

Comparison

Logic

Array

String

Math

Random

Type & Introspection

HashMap

Code Execution

Concurrency

Scheduler

Thread Safety

Error

Output

Time

Multiplayer

Compiler

Clone this wiki locally