File tree Expand file tree Collapse file tree 1 file changed +9
-4
lines changed
Expand file tree Collapse file tree 1 file changed +9
-4
lines changed Original file line number Diff line number Diff line change @@ -42,14 +42,19 @@ function scopeDemo(ServerRequestInterface $request): string
4242
4343 $ response = '' ;
4444 if (file_exists ($ cachePath )) {
45- // Read cached value from file
45+ // Read cached value from file, using file locking to prevent race
46+ // conditions between function executions.
4647 $ response .= "Reading cached value. " . PHP_EOL ;
47- $ instanceVar = file_get_contents ($ cachePath );
48+ $ fh = fopen ($ cachePath , 'r ' );
49+ flock ($ fh , LOCK_EX );
50+ $ instanceVar = stream_get_contents ($ fh );
51+ flock ($ fh , LOCK_UN );
4852 } else {
49- // Compute cached value + write to file
53+ // Compute cached value + write to file, using file locking to prevent
54+ // race conditions between function executions.
5055 $ response .= "Cache empty, computing value. " . PHP_EOL ;
5156 $ instanceVar = _heavyComputation ();
52- file_put_contents ($ cachePath , $ instanceVar );
57+ file_put_contents ($ cachePath , $ instanceVar, LOCK_EX );
5358 }
5459
5560 // Lighter computations can re-run on each function invocation.
You can’t perform that action at this time.
0 commit comments