phasync
Swerve / claim

Method

Swerve::claim

A handle on the name $name, which one holder at a time can hold across the workers.

Description#

public static Swerve::claim(
    string $name
): Claim

Nothing is claimed until acquire() is called: Swerve::claim('name')->acquire() is null, or the held handle. It is held until released, destroyed, or its worker exits or dies.

Parameters#

$name string
Any non-empty string; a namespace of its own, apart from the cache's keys

Return values#

Claim

Errors / Exceptions#

ExceptionWhen
InvalidArgumentExceptionFor an empty name

Examples#

Example 1Only one runs the report
use Swerve\Swerve;

phasync::run(function () {
    // Three coroutines (in a server: workers) want to run the nightly report; one may
    foreach (['a', 'b', 'c'] as $who) {
        phasync::go(function () use ($who) {
            if ($claim = Swerve::claim('nightly-report')->acquire()) {
                echo "$who runs the report\n";
                phasync::sleep(0.1);
            } else {
                echo "$who: someone else is on it\n";
            }
        });                                   // $claim is released when it goes out of scope
    }
});

echo Swerve::claim('nightly-report')->available() ? "free again\n" : "still held\n";
Output
a runs the report
b: someone else is on it
c: someone else is on it
free again
Example 2
if ($claim = Swerve::claim('nightly-report')->acquire()) {
    run_report();
}                                     // released when $claim goes out of scope

See also#

  • ClaimA handle on a name that one holder at a time can hold across the whole server, from Swerve::claim.
  • Swerve::cacheThe cache every worker shares, held by the master process.