summaryrefslogtreecommitdiff
path: root/inc/lock.php
blob: 0d05f52de622023a581d6983a53aafc967aacee6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
class Lock {
  function __construct($key) { global $config;
    if ($config['lock']['enabled'] == 'fs') {
      $key = str_replace('/', '::', (string) $key);
      $key = str_replace("\0", '', $key);

      $this->f = fopen("tmp/locks/$key", "w");
    }
  }

  // Get a shared lock
  function get($nonblock = false) { global $config;
    if ($config['lock']['enabled'] == 'fs') {
      $wouldblock = false;
      flock($this->f, LOCK_SH | ($nonblock ? LOCK_NB : 0), $wouldblock);
      if ($nonblock && $wouldblock) return false;
    }
    return $this;
  }

  // Get an exclusive lock
  function get_ex($nonblock = false) { global $config;
    if ($config['lock']['enabled'] == 'fs') {
      $wouldblock = false;
      flock($this->f, LOCK_EX | ($nonblock ? LOCK_NB : 0), $wouldblock);
      if ($nonblock && $wouldblock) return false;
    }
    return $this;
  }

  // Free a lock
  function free() { global $config;
    if ($config['lock']['enabled'] == 'fs') {
      flock($this->f, LOCK_UN);
    }
    return $this;
  }
}