Alpha ZealPHP is early-stage and under active development. APIs may change between minor versions until v1.0. Feedback and bug reports welcome on GitHub.
API Index — Namespaces, Packages, Reports, Indices

Counter
in package

CounterOpenSwoole\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 $by and return the new value.
get()  : int
Read the current value.
increment()  : int
Atomically add $by and return the new value.
raw()  : Atomic
Return the raw OpenSwoole\Atomic for advanced use.
reset()  : void
Reset to zero.
set()  : void
Set the value (not atomic relative to concurrent add/sub).

Properties

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
bool

decrement()

Atomically subtract $by and return the new value.

public decrement([int $by = 1 ]) : int
Parameters
$by : int = 1
Return values
int

get()

Read the current value.

public get() : int
Return values
int

increment()

Atomically add $by and return the new value.

public increment([int $by = 1 ]) : int
Parameters
$by : int = 1
Return values
int

raw()

Return the raw OpenSwoole\Atomic for advanced use.

public raw() : Atomic
Return values
Atomic

reset()

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
On this page