Last active
July 18, 2023 08:15
-
-
Save videni/33c00216b0bec5498d36c1130899d235 to your computer and use it in GitHub Desktop.
php-save-load-using-require-method-race condition-demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$cachePath = '/tmp/t.php'; | |
$put = function($cachePath){ | |
$code = '<?php'; | |
$code .= "\n\n"; | |
$code .= 'return ' . var_export([], true) . ';'; | |
file_put_contents($cachePath, $code, LOCK_EX); | |
}; | |
$get = function($cachePath) { | |
return require($cachePath); | |
}; | |
$retry = function($cachePath) use($get) { | |
$start = microtime (true); | |
$count = 0; | |
do { | |
$result = $get($cachePath); | |
// Race condition happens when $result is not array. | |
if (is_array($result)) { | |
if ($count >0) { | |
echo sprintf("%s => %s micro seconds".PHP_EOL, $count, (microtime(true) - $start) * 1000000); | |
} | |
return $result; | |
} | |
$count++; | |
} while($result === 1 ); | |
}; | |
$load = function($cachePath) use($retry, $put) { | |
$put($cachePath); // Create the file every time, so we can see the race condition exists | |
return $retry($cachePath); | |
}; | |
for($i=0;$i<1000000;$i++) { | |
$load($cachePath); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
New way