Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Atomic can be used for inter-process variable synchronization.

The integer variable defined with Atomic allows multiple processes access and update it. It is implemented based on CPU atomic instructions. You can use it to implement a high performance counter service with multiple Worker.

The underlayer implementation is CAS: Compare-and-swap (CAS) is an atomic instruction used in multi-threading 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.



  • The Atomic variables have to created before Swoole\Server->start. Then you can access and update it within Worker.
  • You should not define or create a new Atomic within server callbacks like request, receive etc.
  • The integer type is a Int32, but your can use new OpenSwoole\Atomic\Long to create Int64 type.
  • wait and wakeup method is not supported for OpenSwoole\Atomic\Long


$counter = new OpenSwoole\Atomic(123);
echo $counter->add(12)."\n";
echo $counter->sub(11)."\n";
echo $counter->cmpset(122, 999)."\n";
echo $counter->cmpset(124, 999)."\n";
echo $counter->get()."\n";
$counter = new OpenSwoole\Atomic();
$server = new OpenSwoole\Server('', '9501');
    'worker_num' => 1,
    'log_file' => '/dev/null'
$server->on("start", function ($server) use ($counter) {
    if ($counter->add() == 10) {
$server->on("receive", function () use ($counter) {
Last updated on September 1, 2022