Esc
API Index — Namespaces, Packages, Reports, Indices
Counter
in package
Counter — OpenSwoole\Atomic adapter
Lock-free integer counter shared across all worker processes. Uses a spinlock (CAS) internally — safe for concurrent reads/writes from multiple coroutines and workers simultaneously.
IMPORTANT: Instantiate BEFORE $app->run() so the shared memory segment
is inherited by all forked workers.
Usage:
// Before $app->run():
$hits = new Counter();
$errors = new Counter(0);
$version = new Counter(1);
// Anywhere (all workers share the same value):
$hits->increment(); // +1, returns new value
$hits->increment(5); // +5
$hits->decrement(); // -1
$hits->get(); // current value
$hits->set(0); // force-set (not atomic vs concurrent reads)
$hits->reset(); // alias for set(0)
// Conditional update (compare-and-swap):
$hits->compareAndSet($expected, $new); // returns bool
Table of Contents
Properties
- $atomic : Atomic
Methods
- __construct() : mixed
- compareAndSet() : bool
- Compare-and-swap: if current value equals
$expected, set to$new. - decrement() : int
- Atomically subtract
$byand return the new value. - get() : int
- Read the current value.
- increment() : int
- Atomically add
$byand return the new value. - raw() : Atomic
- Return the raw
OpenSwoole\Atomicfor advanced use. - reset() : void
- Reset to zero.
- set() : void
- Set the value (not atomic relative to concurrent add/sub).
Properties
$atomic
private
Atomic
$atomic
Methods
__construct()
public
__construct([int $initial = 0 ]) : mixed
Parameters
- $initial : int = 0
compareAndSet()
Compare-and-swap: if current value equals $expected, set to $new.
public
compareAndSet(int $expected, int $new) : bool
Returns true if the swap happened.
Parameters
- $expected : int
- $new : int
Return values
booldecrement()
Atomically subtract $by and return the new value.
public
decrement([int $by = 1 ]) : int
Parameters
- $by : int = 1
Return values
intget()
Read the current value.
public
get() : int
Return values
intincrement()
Atomically add $by and return the new value.
public
increment([int $by = 1 ]) : int
Parameters
- $by : int = 1
Return values
intraw()
Return the raw OpenSwoole\Atomic for advanced use.
public
raw() : Atomic
Return values
Atomicreset()
Reset to zero.
public
reset() : void
set()
Set the value (not atomic relative to concurrent add/sub).
public
set(int $value) : void
Parameters
- $value : int