2013-05-11 37 views
1

我有一个计数器问题。我需要计算两个变量,用|分隔,但有时计数器不会增加变量的值。带羊群的PHP计数器

numeri.txt(计数器):

6122|742610 

这是PHP脚本:

$filename="numeri.txt"; 
while(!$fp=fopen($filename,'c+')) 
{ 
    usleep(100000); 
} 
while(!flock($fp,LOCK_EX)) 
{ 
    usleep(100000); 
} 
$contents=fread($fp,filesize($filename)); 
ftruncate($fp,0); 
rewind($fp); 
$contents=explode("|",$contents); 
$clicks=$contents[0]; 
$impressions=$contents[1]+1; 
fwrite($fp,$clicks."|".$impressions); 
flock($fp,LOCK_UN); 
fclose($fp); 

我还有一个计数器,它是慢了很多,但数两个值(点击和展示)究竟。有时,计数器numeri.txt会比另一个计数器计入更多的展示次数。为什么?我怎样才能解决这个问题?

+1

检查是否第二,while循环运行到max_execution超时时间,我认为sime类型的死锁/饥饿情况。 – worenga 2013-05-11 09:08:33

+0

当你说“有时候”时 - 你的意思是说某个时候功能增加了,有时却没有?或者你的意思是说每行都不会影响一些行吗? – bestprogrammerintheworld 2013-05-11 09:13:10

+0

我的意思是功能增加了,但是比它应该增加 – Megadv 2013-05-11 09:14:36

回答

0

尝试在解锁前执行刷新。在数据甚至可能被写入之前,你正在解锁,允许另一次执行破坏。

http://php.net/manual/en/function.fflush.php

+0

我在'fwrite'和'flock($ fp,LOCK_UN)之间添加了'fflush($ fp);'但它仍然没有工作......它更多地计数1值 – Megadv 2013-05-15 11:48:08

+0

你是什么意思“计数更多1值”。 – 2013-05-21 21:40:17

0

我们正在利用我们的高流量的网站下面的计算曝光:

<?php 

    $countfile = "counter.txt"; // SET THIS 

    $yearmonthday = date("Y.m.d"); 
    $yearmonth = date("Y.m");; 

    // Read the current counts 
    $countFileHandler = fopen($countfile, "r+"); 
    if (!$countFileHandler) { 
     die("Can't open count file"); 
    } 

    if (flock($countFileHandler, LOCK_EX)) { 
     while (($line = fgets($countFileHandler)) !== false) { 
      list($date, $count) = explode(":", trim($line)); 
      $counts[$date] = $count; 
     } 

     $counts[$yearmonthday]++; 
     $counts[$yearmonth]++; 

     fseek($countFileHandler, 0); 

     // Write the counts back to the file 
     krsort($counts); 
     foreach ($counts as $date => $count) { 
      fwrite($countFileHandler, "$date:$count\n"); 
      fflush($countFileHandler); 
     } 

     flock($countFileHandler, LOCK_UN); 
    } else { 
     echo "Couldn't acquire file lock!"; 
    } 

    fclose($countFileHandler); 
} 
?> 

结果均为每日和每月汇总:

2015.10.02:40513 
2015.10.01:48396 
2015.10:88909