phasync
Blocking calls and the extension / flock

Function

flock

Locks a file, letting other coroutines run while it waits for the lock.

Description#

function flock(
    $stream,
    int $operation,
    ?int &$would_block = null
): bool

Inside a coroutine, a blocking lock request is retried with LOCK_NB and a phasync::yield() between the attempts, until it is granted or fails for another reason than the file being locked. With LOCK_NB, and outside a coroutine, it is the native flock().

Parameters#

$stream
A stream resource
$operation int
LOCK_SH, LOCK_EX or LOCK_UN, optionally with LOCK_NB
$would_block ?int = null
Set by the native flock() when LOCK_NB is given, or outside a coroutine; left alone otherwise

Return values#

bool

Errors / Exceptions#

ExceptionWhen
TypeErrorWhen $stream is not a stream resource

Examples#

Example 1
use function phasync\flock;

$fp = fopen('/tmp/job.lock', 'c');
flock($fp, LOCK_EX);    // other coroutines run while another process holds the lock

See also#