best way to obtain a lock in php

后端 未结 10 974
甜味超标
甜味超标 2020-12-07 15:10

I\'m trying to update a variable in APC, and will be many processes trying to do that.

APC doesn\'t provide locking functionality, so I\'m considering using other me

10条回答
  •  时光说笑
    2020-12-07 15:21

    If you don't mind basing your lock on the filesystem, then you could use fopen() with mode 'x'. Here is an example:

    $f = fopen("lockFile.txt", 'x');
    if($f) {
        $me = getmypid();
        $now = date('Y-m-d H:i:s');
        fwrite($f, "Locked by $me at $now\n");
        fclose($f);
        doStuffInLock();
        unlink("lockFile.txt"); // unlock        
    }
    else {
        echo "File is locked: " . file_get_contents("lockFile.txt");
        exit;
    }
    

    See www.php.net/fopen

提交回复
热议问题