侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

PHP程序中的文件锁、互斥锁、读写锁使用技巧解析

php  /  管理员 发布于 7年前   154

文件锁
全名叫 advisory file lock, 书中有提及。 这类锁比较常见,例如 mysql, php-fpm 启动之后都会有一个pid文件记录了进程id,这个文件就是文件锁。

这个锁可以防止重复运行一个进程,例如在使用crontab时,限定每一分钟执行一个任务,但这个进程运行时间可能超过一分钟,如果不用进程锁解决冲突的话两个进程一起执行就会有问题。

使用PID文件锁还有一个好处,方便进程向自己发停止或者重启信号。例如重启php-fpm的命令为

kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`
发送USR2信号给pid文件记录的进程,信号属于进程通信,会另开一个篇幅。

php的接口为flock,文档比较详细。先看一下定义,bool flock ( resource $handle , int $operation [, int &$wouldblock ] ).

  • $handle是文件系统指针,是典型地由 fopen() 创建的 resource(资源)。这就意味着使用flock必须打开一个文件。
  • $operation 是操作类型。
  • &$wouldblock 如果锁是阻塞的,那么这个变量会设为1.

需要注意的是,这个函数默认是阻塞的,如果想非阻塞可以在 operation 加一个 bitmask LOCK_NB. 接下来测试一下。

$pid_file = "/tmp/process.pid";$pid = posix_getpid();$fp = fopen($pid_file, 'w+');if(flock($fp, LOCK_EX | LOCK_NB)){  echo "got the lock \n";  ftruncate($fp, 0);   // truncate file  fwrite($fp, $pid);  fflush($fp);      // flush output before releasing the lock  sleep(300); // long running process  flock($fp, LOCK_UN);  // 释放锁定} else {  echo "Cannot get pid lock. The process is already up \n";}fclose($fp);

保存为 process.php,运行php process.php &, 此时再次运行php process.php,就可以看到错误提示。flock也有共享锁,LOCK_SH.

互斥锁和读写锁
sync模块中的Mutex:
Mutex是一个组合词,mutual exclusion。用pecl安装一下sync模块, pecl install sync。 文档中的SyncMutex只有两个方法,lock 和 unlock, 我们就直接上代码测试吧。没有用IDE写,所以cs异常丑陋,请无视。

$mutex = new SyncMutex("UniqueName");for($i=0; $i<2; $i++){  $pid = pcntl_fork();  if($pid <0){    die("fork failed");  }elseif ($pid>0){    echo "parent process \n";  }else{    echo "child process {$i} is born. \n";    obtainLock($mutex, $i);  }}while (pcntl_waitpid(0, $status) != -1) {   $status = pcntl_wexitstatus($status);   echo "Child $status completed\n"; }function obtainLock ($mutex, $i){  echo "process {$i} is getting the mutex \n";  $res = $mutex->lock(200);  sleep(1);  if (!$res){    echo "process {$i} unable to lock mutex. \n";  }else{    echo "process {$i} successfully got the mutex \n";    $mutex->unlock();  }  exit();}

保存为mutex.php, run php mutex.php, output is

parent process parent process child process 1 is born. process 1 is getting the mutex child process 0 is born. process 0 is getting the mutex process 1 successfully got the mutex Child 0 completedprocess 0 unable to lock mutex. Child 0 completed

这里子进程0和1不一定谁在前面。但是总有一个得不到锁。这里SyncMutex::lock(int $millisecond)的参数是 millisecond, 代表阻塞的时长, -1 为无限阻塞。

sync模块中的读写锁:
SyncReaderWriter的方法类似,readlock, readunlock, writelock, writeunlock,成对出现即可,没有写测试代码,应该和Mutex的代码一致,把锁替换一下就可以。

sync模块中的Event:
感觉和golang中的Cond比较像,wait()阻塞,fire()唤醒Event阻塞的一个进程。有一篇好文介绍了Cond, 可以看出Cond就是锁的一种固定用法。SyncEvent也一样。
php文档中的例子显示,fire()方法貌似可以用在web应用中。

上测试代码

for($i=0; $i<3; $i++){  $pid = pcntl_fork();  if($pid <0){    die("fork failed");  }elseif ($pid>0){    //echo "parent process \n";  }else{    echo "child process {$i} is born. \n";    switch ($i) {    case 0:      wait();      break;    case 1:      wait();      break;    case 2:      sleep(1);      fire();      break;    }  }}while (pcntl_waitpid(0, $status) != -1) {   $status = pcntl_wexitstatus($status);   echo "Child $status completed\n"; }function wait(){  $event = new SyncEvent("UniqueName");  echo "before waiting. \n";  $event->wait();  echo "after waiting. \n";  exit();}function fire(){  $event = new SyncEvent("UniqueName");  $event->fire();  exit();}

这里故意少写一个fire(), 所以程序会阻塞,证明了 fire() 一次只唤醒一个进程。

pthreads模块
锁定和解锁互斥量:

函数:

pthread_mutex_lock (mutex) pthread_mutex_trylock (mutex) pthread_mutex_unlock (mutex) 

用法:

线程用pthread_mutex_lock()函数去锁定指定的mutex变量,若该mutex已经被另外一个线程锁定了,该调用将会阻塞线程直到mutex被解锁。
pthread_mutex_trylock() will attempt to lock a mutex. However, if the mutex is already locked, the routine will return immediately with a "busy" error code. This routine may be useful in pthread_mutex_trylock().

  尝试着去锁定一个互斥量,然而,若互斥量已被锁定,程序会立刻返回并返回一个忙错误值。该函数在优先级改变情况下阻止死锁是非常有用的。线程可以用pthread_mutex_unlock()解锁自己占用的互斥量。在一个线程完成对保护数据的使用,而其它线程要获得互斥量在保护数据上工作时,可以调用该函数。若有一下情形则会发生错误:

  • 互斥量已经被解锁
  • 互斥量被另一个线程占用

互斥量并没有多么“神奇”的,实际上,它们就是参与的线程的“君子约定”。写代码时要确信正确地锁定,解锁互斥量。

Q:有多个线程等待同一个锁定的互斥量,当互斥量被解锁后,那个线程会第一个锁定互斥量?
A:除非线程使用了优先级调度机制,否则,线程会被系统调度器去分配,那个线程会第一个锁定互斥量是随机的。

#include #include #include #include typedef struct ct_sum {   int sum;   pthread_mutex_t lock; }ct_sum; void * add1(void *cnt) {      pthread_mutex_lock(&(((ct_sum*)cnt)->lock));   for(int i=0; i < 50; i++)   {    (*(ct_sum*)cnt).sum += i;     }   pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));   pthread_exit(NULL);   return 0; } void * add2(void *cnt) {      pthread_mutex_lock(&(((ct_sum*)cnt)->lock));   for(int i=50; i<101; i++)   {       (*(ct_sum*)cnt).sum += i;    }   pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));   pthread_exit(NULL);   return 0; }  int main(void) {  pthread_t ptid1, ptid2;   ct_sum cnt;   pthread_mutex_init(&(cnt.lock), NULL);   cnt.sum=0;    pthread_create(&ptid1, NULL, add1, &cnt);   pthread_create(&ptid2, NULL, add2, &cnt);     pthread_join(ptid1,NULL);   pthread_join(ptid2,NULL);  printf("sum %d\n", cnt.sum);  pthread_mutex_destroy(&(cnt.lock));   return 0; }

信号量
sync模块中的信号量:
SyncSemaphore文档中显示,它和Mutex的不同之处,在于Semaphore一次可以被多个进程(或线程)得到,而Mutex一次只能被一个得到。所以在SyncSemaphore的构造函数中,有一个参数指定信号量可以被多少进程得到。
public SyncSemaphore::__construct ([ string $name [, integer $initialval [, bool $autounlock ]]] ) 就是这个$initialval (initial value)

$lock = new SyncSemaphore("UniqueName", 2);for($i=0; $i<2; $i++){  $pid = pcntl_fork();  if($pid <0){    die("fork failed");  }elseif ($pid>0){    echo "parent process \n";  }else{    echo "child process {$i} is born. \n";    obtainLock($lock, $i);  }}while (pcntl_waitpid(0, $status) != -1) {   $status = pcntl_wexitstatus($status);   echo "Child $status completed\n"; }function obtainLock ($lock, $i){  echo "process {$i} is getting the lock \n";  $res = $lock->lock(200);  sleep(1);  if (!$res){    echo "process {$i} unable to lock lock. \n";  }else{    echo "process {$i} successfully got the lock \n";    $lock->unlock();  }  exit();}

这时候两个进程都能得到锁。

  • sysvsem模块中的信号量
  • sem_get 创建信号量
  • sem_remove 删除信号量(一般不用)
  • sem_acquire 请求得到信号量
  • sem_release 释放信号量。和 sem_acquire 成对使用。
$key = ftok('/tmp', 'c');$sem = sem_get($key);for($i=0; $i<2; $i++){  $pid = pcntl_fork();  if($pid <0){    die("fork failed");  }elseif ($pid>0){    //echo "parent process \n";  }else{    echo "child process {$i} is born. \n";    obtainLock($sem, $i);  }}while (pcntl_waitpid(0, $status) != -1) {   $status = pcntl_wexitstatus($status);   echo "Child $status completed\n"; }sem_remove($sem); // finally remove the semfunction obtainLock ($sem, $i){  echo "process {$i} is getting the sem \n";  $res = sem_acquire($sem, true);  sleep(1);  if (!$res){    echo "process {$i} unable to get sem. \n";  }else{    echo "process {$i} successfully got the sem \n";    sem_release($sem);  }  exit();}

这里有一个问题,sem_acquire()第二个参数$nowait默认为false,阻塞。我设为了true,如果得到锁失败,那么后面的sem_release会报警告 PHP Warning:  sem_release(): SysV semaphore 4 (key 0x63000081) is not currently acquired in /home/jason/sysvsem.php on line 33, 所以这里的release操作必须放在得到锁的情况下执行,前面的几个例子中没有这个问题,没得到锁执行release也不会报错。当然最好还是成对出现,确保得到锁的情况下再release。
此外,ftok这个方法的参数有必要说明下,第一个 必须是existing, accessable的文件, 一般使用项目中的文件,第二个是单字符字符串。返回一个int。

输出为

parent process parent process child process 1 is born. process 1 is getting the mutex child process 0 is born. process 0 is getting the mutex process 1 successfully got the mutex Child 0 completedprocess 0 unable to lock mutex. Child 0 completed

您可能感兴趣的文章:

  • php逐行读取txt文件写入数组的方法
  • PHP文件读写操作之文件写入代码
  • 老生常谈PHP 文件写入和读取(必看篇)
  • PHP文件打开、关闭、写入的判断与执行代码
  • php写入数据到CSV文件的方法
  • php 写入缓存文件、读取缓存文件的函数代码
  • 解析PHP中如何将数组变量写入文件
  • PHP中读写文件实现代码
  • PHP中文件读、写、删的操作(PHP中对文件和目录操作)
  • php文件操作之文件写入字符串、数组的方法分析


  • 上一条:
    调用WordPress函数统计文章访问量及PHP原生计数器的实现
    下一条:
    PHP编程中尝试程序并发的几种方式总结
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客