Using Swoole Atomic for Lock‑Free Counters in PHP
Because PHP lacks native multithreading, Swoole adopts a multi‑process model and provides the Atomic class for lock‑free integer operations, which can be shared across worker processes; this guide explains its purpose, configuration, usage patterns, code examples, and important pitfalls.
Swoole runs PHP in a multi‑process mode since the language itself does not support true multithreading. In this model each worker process has isolated memory, so modifying global or super‑global variables in one worker does not affect others.
The Atomic class is a low‑level atomic counter provided by Swoole. It enables lock‑free increment and decrement of integers using CPU atomic instructions supplied by gcc/clang, without requiring explicit locks.
Key Features
Uses shared memory, allowing the counter to be accessed across different worker processes.
Built on gcc/clang‑provided CPU atomic instructions, eliminating the need for mutexes.
Must be created before Server->start so that it is available in worker processes.
Defaults to a 32‑bit unsigned type; for 64‑bit signed integers, use Swoole\Atomic\Long.
Usage Example
Below is a minimal example that creates an Atomic instance, starts a Swoole server, and shuts down the server when the counter reaches a specific value.
<?php
$atomic = new Swoole\Atomic();
$serv = new Swoole\Server('127.0.0.1', 9501);
$serv->set([
'worker_num' => 1,
'log_file' => '/dev/null'
]);
$serv->on('start', function ($serv) use ($atomic) {
if ($atomic->add() == 2) {
$serv->shutdown();
}
});
$serv->on('ManagerStart', function ($serv) use ($atomic) {
if ($atomic->add() == 2) {
$serv->shutdown();
}
});
$serv->on('ManagerStop', function ($serv) {
echo "shutdown
";
});
$serv->on('receive', function ($serv) {
// TODO: handle incoming data
});
$serv->start();
?>Important Caveats
Do not create an Atomic instance inside callbacks such as onReceive; doing so will cause the counter to be allocated repeatedly, leading to memory growth and eventual leaks.
The 64‑bit signed version ( Swoole\Atomic\Long) does not support the wait and wakeup methods.
This information equips developers with the necessary understanding to safely integrate lock‑free counters into high‑performance PHP services built with Swoole.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
