Synchronized block in php 7

后端 未结 4 1891
不知归路
不知归路 2021-01-20 08:20

i come from a java background where there were synchronized blocks:

The \"Synchronized\" keywords prevents concurrent access to a block of code or o

4条回答
  •  佛祖请我去吃肉
    2021-01-20 08:51

    Other people answer with lots of words, but no code. Why don't you try this?

    function synchronized($handler)
    {
        $name = md5(json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,1)[0]));
        $filename = sys_get_temp_dir().'/'.$name.'.lock';
        $file = fopen($filename, 'w');
        if ($file === false) {
            return false;
        }
        $lock = flock($file, LOCK_EX);
        if (!$lock) {
            fclose($file);
            return false;
        }
        $result = $handler();
        flock($file, LOCK_UN);
        fclose($file);
        return $result;
    }
    
    function file_put_contents_atomic($filename, $string)
    {
        return synchronized(function() use ($filename,$string) {
            $tempfile = $filename . '.temp';
            $result = file_put_contents($tempfile, $string);
            $result = $result && rename($tempfile, $filename);
            return $result;
        });
    }
    

    The above code does an atomic file_put_contents using a custom "synchronized" function.

    Source: https://tqdev.com/2018-java-synchronized-block-in-php

提交回复
热议问题