程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> 進程鎖定問題分析研究

進程鎖定問題分析研究

編輯:關於PHP編程


<?php
/**
* 進行寫鎖定的測試
* 打開線程1
*/
require("file_lock.php");
$lock = new File_Lock(dirname(dirname(__FILE__)) . "/FileLock.lock");
/** 單個線程鎖定的速度 1s 鐘 3萬次。 **/
/** 兩個線程寫,兩萬的數據 大概要 7s 鐘*/
/** 一個線程寫,一萬的數據 大概要 3.9s 鐘,居然兩個文件同時寫,要快一點*/
/** 不進行鎖定,一個進程 寫大概要 2.8s 鐘,加鎖是有代價的。 */
/** 不進行鎖定,兩個進程 分布不是很均勻,而且大多數都沖突 */
$lock->writeLock();
$lock->increment();
$lock->unlock();
while ($lock->get() < 2) {
usleep(1000);
}
sleep(1);
echo "begin to runing n";
$t1 = microtime(true);
for ($i = 0; $i < 10000; $i++)
{
$lock->writeLock();
$lock->increment(1);
$lock->unlock();
}
$t2 = microtime(true) - $t1;
echo $t2;
?>


<?php
class File_Lock
{
private $name;
private $handle;
private $mode;
function __construct($filename, $mode = 'a+b')
{
global $php_errormsg;
$this->name = $filename;
$path = dirname($this->name);
if ($path == '.' || !is_dir($path)) {
global $config_file_lock_path;
$this->name = str_replace(array("/", ""), array("_", "_"), $this->name);
if ($config_file_lock_path == null) {
$this->name = dirname(__FILE__) . "/lock/" . $this->name;
} else {
$this->name = $config_file_lock_path . "/" . $this->name;
}
}
$this->mode = $mode;
$this->handle = @fopen($this->name, $mode);
if ($this->handle == false) {
throw new Exception($php_errormsg);
}
}
public function close()
{
if ($this->handle !== null ) {
@fclose($this->handle);
$this->handle = null;
}
}
public function __destruct()
{
$this->close();
}
public function lock($lockType, $nonBlockingLock = false)
{
if ($nonBlockingLock) {
return flock($this->handle, $lockType | LOCK_NB);
} else {
return flock($this->handle, $lockType);
}
}
public function readLock()
{
return $this->lock(LOCK_SH);
}
public function writeLock($wait = 0.1)
{
$startTime = microtime(true);
$canWrite = false;
do {
$canWrite = flock($this->handle, LOCK_EX);
if(!$canWrite) {
usleep(rand(10, 1000));
}
} while ((!$canWrite) && ((microtime(true) - $startTime) < $wait));
}
/**
* if you want't to log the number under multi-thread system,
* please open the lock, use a+ mod. then fopen the file will not
* destroy the data.
*
* this function increment a delt value , and save to the file.
*
* @param int $delt
* @return int
*/
public function increment($delt = 1)
{
$n = $this->get();
$n += $delt;
$this->set($n);
return $n;
}
public function get()
{
fseek($this->handle, 0);
return (int)fgets($this->handle);
}
public function set($value)
{
ftruncate($this->handle, 0);
return fwrite($this->handle, (string)$value);
}
public function unlock()
{
if ($this->handle !== null ) {
return flock($this->handle, LOCK_UN);
} else {
return true;
}
}
}
?>

 


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved