flock does not block

74 views Asked by At

Please explain why the code below blocks first execution (1607061065) and does not block the second one (1664361639) (the output is attached):

<?php
$fileName = "file.txt";

$fp = fopen($fileName, "a");
if (flock($fp, LOCK_EX | LOCK_NB)) {
    $runId = rand();
    fwrite(
        $fp,
        "processing task [runId]: $runId; [pid]: ". getmypid() ." started \n" .
        (new DateTime())->format(DateTime::ATOM) . " \n\n"
    );

    sleep(3);
    flock($fp, LOCK_UN);
    fwrite(
        $fp,
        "processing task [runId]: $runId; [pid]: ". getmypid() ." finished \n" .
        (new DateTime())->format(DateTime::ATOM) . " \n\n"
    );
    fclose($fp);
    exit;
}
fwrite(
    $fp,
    "script is busy [pid]: ". getmypid() ." \n" .
    (new DateTime())->format(DateTime::ATOM) . " \n\n"
);

I am running this via ab utility which is able to send request concurrently:

ab -c 3 -n 8 http://localhost/

(it is run by 3 instances in parallel 8 times)

And this is what I have in file.txt after execution is finished:

processing task [runId]: 1607061065; [pid]: 2507 started
2022-12-22T17:03:22+00:00

processing task [runId]: 1607061065; [pid]: 2507 finished
2022-12-22T17:03:25+00:00

processing task [runId]: 1664361639; [pid]: 2503 started
2022-12-22T17:03:25+00:00

script is busy [pid]: 2507
2022-12-22T17:03:25+00:00

script is busy [pid]: 2502
2022-12-22T17:03:25+00:00

script is busy [pid]: 2502
2022-12-22T17:03:25+00:00

script is busy [pid]: 2507
2022-12-22T17:03:25+00:00

script is busy [pid]: 2502
2022-12-22T17:03:25+00:00

script is busy [pid]: 2507
2022-12-22T17:03:25+00:00

processing task [runId]: 1664361639; [pid]: 2503 finished
2022-12-22T17:03:28+00:00

Why 1607061065 blocks the first execution and why there is a second process exist which acuires lock 1664361639 which does not block the execution.

Thanks in advance

0

There are 0 answers