synchronized() публичный Метод

The code has to be designed in a way that it can be repeated without any side effects. When the CAS operation was successful it should notify this mutex by calling {@link CASMutex::notify()}. I.e. the only side effects of the code may happen after a successful CAS operation. The CAS operation itself is a valid side effect as well. If the code throws an exception it will stop repeating the execution. Example: $mutex = new CASMutex(); $mutex->synchronized(function () use ($memcached, $mutex, $amount) { $balance = $memcached->get("balance", null, $casToken); $balance -= $amount; if (!$memcached->cas($casToken, "balance", $balance)) { return; } $mutex->notify(); });
public synchronized ( callable $code ) : mixed
$code callable The synchronized execution block.
Результат mixed The return value of the execution block.
Пример #1
0
 /**
  * Tests that the code is executed more times.
  *
  * @test
  */
 public function testIteration()
 {
     $i = 0;
     $mutex = new CASMutex();
     $mutex->synchronized(function () use($mutex, &$i) {
         $i++;
         if ($i > 1) {
             $mutex->notify();
         }
     });
     $this->assertEquals(2, $i);
 }