1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19:
20: final class NCriticalSection
21: {
22:
23: private static $criticalSections;
24:
25:
26:
27: 28: 29:
30: final public function __construct()
31: {
32: throw new LogicException("Cannot instantiate static class " . get_class($this));
33: }
34:
35:
36:
37: 38: 39: 40:
41: public static function enter()
42: {
43: if (self::$criticalSections) {
44: throw new InvalidStateException('Critical section has already been entered.');
45: }
46: 47: $handle = substr(PHP_OS, 0, 3) === 'WIN'
48: ? @fopen(NETTE_DIR . '/lockfile', 'w')
49: : @fopen(__FILE__, 'r'); 50:
51: if (!$handle) {
52: throw new InvalidStateException("Unable initialize critical section.");
53: }
54: flock(self::$criticalSections = $handle, LOCK_EX);
55: }
56:
57:
58:
59: 60: 61: 62:
63: public static function leave()
64: {
65: if (!self::$criticalSections) {
66: throw new InvalidStateException('Critical section has not been initialized.');
67: }
68: flock(self::$criticalSections, LOCK_UN);
69: fclose(self::$criticalSections);
70: self::$criticalSections = NULL;
71: }
72:
73: }