PHP 5.x同步文件访问(无数据库) [英] PHP 5.x syncronized file access (no database)

查看:104
本文介绍了PHP 5.x同步文件访问(无数据库)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最熟悉Java,C和C ++,其中有一些方法可以控制在任何给定时间只有一个线程正在访问资源.现在,我正在寻找类似的东西,但是在PHP 5.x中.

I'm mostly familiar with Java, C and C++ in which there are ways to control that only one thread is accessing a resource at any given time. Now I'm in search for something similar but in PHP 5.x.

举一个例子来说明我的问题:

To formulate my problem with one example:

我有一个ASCII文件,它仅存储一个数字,即页面加载计数器的值.在应用程序部署时,文件将仅保留0.对于每次访问,该值将递增1.目标是跟踪页面加载.

I have an ASCII-file which only stores a number, the value of a page load counter. At application deployment the file will simply hold a 0. For each access the value will be incremented by one. The goal is to keep track of page loads.

当许多用户同时访问包含计数器的页面时,就会出现问题.当线程A读取当前值时,假设它是11,另一个我们称为B的线程仍读取该值,然后第一个线程A增加读取值并将12写入文件并关闭它.然后,第二个线程B将读取值11递增为12,然后将其写入文件.值12实际上应该是13时存储在文件中.

The problem comes when many users are concurrently accessing the page containing the counter. When thread A has read the current value, let's say it is 11, another thread which we call B reads the value, still 11. Then the first thread A increments the read value and writes 12 in the file and closes it. Then the second thread B, increments the read value, which was 11, gets 12 and writes that into the file. The value 12 is stored in the file, when it really should have been 13.

在另一种编程语言中,我会使用互斥锁解决此问题.我了解模块中有互斥体,共享内存和其他功能.但是我想要一个可以在大多数服务器"上运行的解决方案.平台无关.安装在最便宜的网络主机上.有解决这个问题的好方法吗?如果没有,如果不使用数据库,您会采取哪种方式?

In another programming language I would have solved this using a mutex. I understand there are mutexes, shared memory and other funcionality as part of modules. But I would like a solution which works on "most servers" out there. Platform independent. Installed on most cheap web hosts. Is there a good solution to this problem? And if there isn't, which way would you take if using a database is not an option?

推荐答案

您可以尝试php的flock变体( http: //www.php.net/flock )

You could try php's variant of flock (http://www.php.net/flock)

我会设想类似的内容(这假设文件/tmp/counter.txt已经存在并且文件中有一个计数器):

I would envision something similar to (this assumes that the file /tmp/counter.txt already exists and has a counter in the file):

<?php

$fp = fopen("/tmp/counter.txt", "r+");

echo "Attempt to lock\n";
if (flock($fp, LOCK_EX)) {
  echo "Locked\n";
  // Read current value of the counter and increment
  $cntr = fread($fp, 80);
  $cntr = intval($cntr) + 1;

  // Pause to prove that race condition doesn't exist
  sleep(5);

  // Write new value to the file
  ftruncate($fp, 0);
  fseek($fp, 0, SEEK_SET);
  fwrite($fp, $cntr);
  flock($fp, LOCK_UN); // release the lock
  fclose($fp);
}

?>

这篇关于PHP 5.x同步文件访问(无数据库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆