Atomic
can be used for interprocess 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 implemention is CAS
: 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
Swoole\Atomic\add
Swoole\Atomic\sub
Swoole\Atomic\get
Swoole\Atomic\set
Swoole\Atomic\wait
Swoole\Atomic\wakeup
Swoole\Atomic\cmpset
Swoole\Atomic\Long->__construct
Swoole\Atomic\Long\add
Swoole\Atomic\Long\sub
Swoole\Atomic\Long\get
Swoole\Atomic\Long\set
Swoole\Atomic\Long\cmpset
Atomic
variables have to created before Swoole\Server->start. Then you can access and update it within Worker
.Atomic
within server callbacks like request
, receive
etc.new Swoole\Atomic\Long
to create Int64 type.wait
and wakeup
method is not supported for Swoole\Atomic\Long
<?php
$counter = new Swoole\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";
<?php
$counter = new Swoole\Atomic();
$server = new Swoole\Server('127.0.0.1', '9501');
$server->set([
'worker_num' => 1,
'log_file' => '/dev/null'
]);
$server->on("start", function ($server) use ($counter) {
if ($counter->add() == 10) {
$server->shutdown();
}
});
$server->on("receive", function () use ($counter) {
$counter->add();
});
$server->start();