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
42
42
43
43
$ response = '' ;
44
44
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.
46
47
$ 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 );
48
52
} 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.
50
55
$ response .= "Cache empty, computing value. " . PHP_EOL ;
51
56
$ instanceVar = _heavyComputation ();
52
- file_put_contents ($ cachePath , $ instanceVar );
57
+ file_put_contents ($ cachePath , $ instanceVar, LOCK_EX );
53
58
}
54
59
55
60
// Lighter computations can re-run on each function invocation.
You can’t perform that action at this time.
0 commit comments