What is the correct way to execute a lock file (to eliminate a critical section)

Turning to flock (): deleting a locked file without a race condition? And Will the flock'ed file be unlocked if the process dies unexpectedly? ,

I am creating the following code. My intention is to allow only one thread / single process to execute critical section code for any given time.

<?php

// Exclusive locking based on function parameters.
$lockFileName = '/tmp/cheok.lock';
// Create if doesn't exist.
$lockFile = fopen($lockFileName, "w+");

if (!flock($lockFile, LOCK_EX)) {
    throw new \RumtimeException("Fail to perform flock on $lockFileName");
}

echo "start critical section...\n";
sleep(10);
echo "end critical section.\n";

// Warning: unlink(/tmp/cheok.lock): No such file or directory in
unlink($lockFileName);
flock($lockFile, LOCK_UN);

I always get a warning

Warning: unlink (/tmp/cheok.lock): there is no such file or directory in

when the second wait process continues, the 1st process already deletes the physical disk file. The second process tries to execute a unlinkfile that is already deleted by the 1st process.

, , , fopen, unlink?

, ?

+4
1

, pthreads.

-, . PHP , .

man- flock

flock() ; , flock() / .

, , cron , ... .

( pthreads) , pthreads API .

, :

<?php
class Test extends Thread {

    public function __construct(Threaded $monitor) {
        $this->monitor = $monitor;
    }

    public function run () {
        $this->monitor->synchronized(function(){
            for ($i = 0; $i < 1000; $i++)
                printf("%s #%lu: %d\n",
                    __CLASS__, $this->getThreadId(), $i);
        });
    }

    private $monitor;
}

$threads = [];
$monitor = new Threaded();
for ($i = 0; $i < 8; $i++) {
    $threads[$i] = new Test($monitor);
    $threads[$i]->start();
}

foreach ($threads as $thread) 
    $thread->join();

$monitor, , Threaded, , :

Test #140561163798272: 0
<-- snip for brevity -->
Test #140561163798272: 999
Test #140561151424256: 0
<-- snip for brevity -->
Test #140561151424256: 999
Test #140561138841344: 0
<-- snip for brevity -->
Test #140561138841344: 999
Test #140561059149568: 0
<-- snip for brevity -->
Test #140561059149568: 999
Test #140561050756864: 0
<-- snip for brevity -->
Test #140561050756864: 999
Test #140561042364160: 0
<-- snip for brevity -->
Test #140561042364160: 999
Test #140561033971456: 0
<-- snip for brevity -->
Test #140561033971456: 999
Test #140561025578752: 0
<-- snip for brevity -->
Test #140561025578752: 999

, Thread Closure, Threaded::synchronized.

+3

Source: https://habr.com/ru/post/1609943/


All Articles