# shared ## Category Thread Safety ## Arity **Declaration keyword** — not a runtime command in the traditional sense. ``` shared _variableName = ; ``` ## 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](add.md), [sub](sub.md), [get](get.md), [set](set.md), [compareSwap](compareSwap.md) — 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 ```sqf shared _counter = 0; shared _flag = false; shared _total = 0.0; ``` ### Atomic increment ```sqf shared _counter = 0; _counter add 1; // atomic — safe from any scheduler _counter add 5; // atomic add ``` ### Atomic read ```sqf _val = get _counter; // atomic read ``` ### Atomic compare-and-swap ```sqf 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 ```sqf 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](freeze.md)/[sendTo](sendTo.md) for complex data structures. ## Thread Safety Fully thread-safe by design. All operations on shared variables are atomic or CAS-based. ## See Also - [add](add.md) — atomic add - [sub](sub.md) — atomic subtract - [get](get.md) — atomic read - [set](set.md) — write (not atomic on shared) - [compareSwap](compareSwap.md) — atomic CAS - [freeze](freeze.md) — immutable array sharing