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

shared

Category

Thread Safety

Arity

Declaration keyword — not a runtime command in the traditional sense.

shared _variableName = <initialValue>;

Description

Declares a CAS-based atomic variable. Like private but creates a thread-safe variable backed by compare-and-swap operations. Shared variables can be safely read and modified from multiple schedulers without explicit locking.

Operations on shared variables — add, sub, get, set, compareSwap — are atomic and thread-safe.

How It Works

The compiler emits special opcodes for shared variable declaration and access. The underlying storage uses Interlocked operations for atomicity. Shared variables are not full .NET object references — they wrap numeric values with CAS semantics.

Usage

Declaration

shared _counter = 0;
shared _flag = false;
shared _total = 0.0;

Atomic increment

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

Atomic read

_val = get _counter;           // atomic read

Atomic compare-and-swap

shared _lock = 0;
// Try to acquire "lock"
_success = _lock compareSwap [0, 1];  // true if acquired, false if already taken
if (_success) then {
    // critical section
    _lock set [nil, 0];        // release (NOT atomic — only one writer)
};

Multi-scheduler counter

shared _visitors = 0;

// Scheduler 1:
_visitors add 1;

// Scheduler 2:
_visitors add 1;

// Scheduler 3:
_total = get _visitors;        // 2 (atomic read)

Limitations

  • Shared values are numeric only (numbers and booleans).
  • set on shared is not atomic — use compareSwap for concurrent writes.
  • Not a replacement for full locking — use freeze/sendTo for complex data structures.

Thread Safety

Fully thread-safe by design. All operations on shared variables are atomic or CAS-based.

See Also

  • add — atomic add
  • sub — atomic subtract
  • get — atomic read
  • set — write (not atomic on shared)
  • compareSwap — atomic CAS
  • freeze — immutable array sharing

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