Swoole Atomic

Integer variable allows multiple processes to atomically test and modify. Implemented based on CPU atomic instructions. It is always used as counter updated by multiple Swoole Workers.

The Swoole atomic variables have to defined before Swoole\Server->start.

Compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the contents of a memory location with a given value and, only if they are the same, modifies the contents of that memory location to a new given value.

Swoole\Atomic->__construct(int $init_value = 0)

Construct a swoole atomic object.

Swoole\Atomic->add(int $add_value = 1)

Add a number to the value fo the atomic object.

Swoole\Atomic->sub(int $sub_value = 1)

Subtract a number to the value of the atomic object.

Swoole\Atomic->get()

Get the current value of the atomic object.

Swoole\Atomic->set(int $value)

Set the value to the atomic object.

Swoole\Atomic->cmpset(int $cmp_value, int $set_value)

Compare and set the value of the atomic object. See more about Compare and set.

Swoole\Atomic->wait(float $timeout = -1) : bool

Wait the value to be changed for a duration.

Swoole\Atomic->wakeup(int $n = 1)

Wakeup processes waiting on the lock.

Example

<?php
$atomic = new Swoole\Atomic(123);
echo $atomic->add(12)."\n";
echo $atomic->sub(11)."\n";
echo $atomic->cmpset(122, 999)."\n";
echo $atomic->cmpset(124, 999)."\n";
echo $atomic->get()."\n";

Swoole\Atomic\Long for INT64 is added version >= 1.9.20

Swoole\Atomic\Long->__construct(int $init_value = 0)

Construct a swoole atomic object.

Swoole\Atomic\Long->add(int $add_value = 1)

Add a number to the value fo the atomic object.

Swoole\Atomic\Long->sub(int $sub_value = 1)

Subtract a number to the value of the atomic object.

Swoole\Atomic\Long->get()

Get the current value of the atomic object.

Swoole\Atomic\Long->set(int $value)

Set the value to the atomic object.

Swoole\Atomic\Long->cmpset(int $cmp_value, int $set_value)

Compare and set the value of the atomic object. See more about Compare and set.