-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathclass.phplock.php
More file actions
113 lines (111 loc) · 2.6 KB
/
Copy pathclass.phplock.php
File metadata and controls
113 lines (111 loc) · 2.6 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/**
* PHPLock进程锁
* 本进程锁用来解决php在并发时候的锁控制
* 他根据文件锁来模拟多个进程之间的锁定,效率不是非常高。如果文件建立在内存中,可以大大提高效率。
* PHPLOCK在使用过程中,会在指定的目录产生$hashNum个文件用来产生对应粒度的锁。不同锁之间可以并行执行。
* 这有点类似mysql的innodb的行级锁,不同行的更新可以并发的执行。
* @link http://code.google.com/p/phplock/
* @author sunli
* @blog http://sunli.cnblogs.com
* @svnversion $Id$
* @version v1.0 beta1
* @license Apache License Version 2.0
* @copyright sunli1223@gmail.com
*/
class PHPLock {
/**
* 锁文件路径
*
* @var String
*/
private $path = null;
/**
* 文件句柄
*
* @var resource
*/
private $fp = null;
/**
* 锁的粒度控制,设置的越大粒度越小
*
* @var int
*/
private $hashNum = 100;
private $name;
private $eAccelerator = false;
/**
* 构造函数
*
* @param string $path 锁的存放目录,以"/"结尾
* @param string $name 锁名称,一般在对资源加锁的时候,会命名一个名字,这样不同的资源可以并发的进行。
*/
public function __construct($path, $name) {
$this->path = $path . ($this->mycrc32 ( $name ) % $this->hashNum) . '.txt';
$this->eAccelerator = function_exists ( "eaccelerator_lock" );
$this->name = $name;
}
/**
* crc32的封装
*
* @param string $string
* @return int
*/
private function mycrc32($string) {
$crc = abs ( crc32 ( $string ) );
if ($crc & 0x80000000) {
$crc ^= 0xffffffff;
$crc += 1;
}
return $crc;
}
/**
* 初始化锁,是加锁前的必须步骤
* 打开一个文件
*
*/
public function startLock() {
if (! $this->eAccelerator) {
$this->fp = fopen ( $this->path, "w+" );
}
}
/**
* 开始加锁
*
* @return bool 加锁成功返回true,失败返回false
*/
public function lock() {
if (! $this->eAccelerator) {
if ($this->fp === false) {
return false;
}
return flock ( $this->fp, LOCK_EX );
} else {
return eaccelerator_lock ( $this->name );
}
}
/**
* 释放锁
*
*/
public function unlock() {
if (! $this->eAccelerator) {
if ($this->fp !== false) {
flock ( $this->fp, LOCK_UN );
clearstatcache ();
}
} else {
return eaccelerator_unlock ( $this->name );
}
}
/**
* 结束锁控制
*
*/
public function endLock() {
if (! $this->eAccelerator) {
fclose ( $this->fp );
}
}
}
?>