首页 > 开发 > PHP > 正文

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

2024-05-04 22:01:43
字体:大 中 小
来源:转载
供稿:网友

文件锁

全名叫 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. 接下来测试一下。

  1. $pid_file = "/tmp/process.pid"; 
  2.  
  3. $pid = posix_getpid(); 
  4.  
  5. $fp = fopen($pid_file, 'w+'); 
  6.  
  7. if(flock($fp, LOCK_EX | LOCK_NB)){ 
  8.  
  9.   echo "got the lock /n"; 
  10.  
  11.   ftruncate($fp, 0);   // truncate file 
  12.  
  13.   fwrite($fp, $pid); 
  14.  
  15.   fflush($fp);      // flush output before releasing the lock 
  16.  
  17.   sleep(300); // long running process 
  18.  
  19.   flock($fp, LOCK_UN);  // 释放锁定 
  20.  
  21. } else { 
  22.  
  23.   echo "Cannot get pid lock. The process is already up /n"; 
  24.  
  25. } 
  26.  
  27. 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异常丑陋,请无视。

  1. $mutex = new SyncMutex("UniqueName"); 
  2.  
  3. for($i=0; $i<2; $i++){ 
  4.  
  5.   $pid = pcntl_fork(); 
  6.  
  7.   if($pid <0){ 
  8.  
  9.     die("fork failed"); 
  10.  
  11.   }elseif ($pid>0){ 
  12.  
  13.     echo "parent process /n"; 
  14.  
  15.   }else{ 
  16.  
  17.     echo "child process {$i} is born. /n"; 
  18.  
  19.     obtainLock($mutex, $i); 
  20.  
  21.   } 
  22.  
  23. } 
  24.  
  25. while (pcntl_waitpid(0, $status) != -1) {  
  26.  
  27.   $status = pcntl_wexitstatus($status);  
  28.  
  29.   echo "Child $status completed/n";  
  30.  
  31. } 
  32.  
  33. function obtainLock ($mutex, $i){ 
  34.  
  35.   echo "process {$i} is getting the mutex /n"; 
  36.  
  37.   $res = $mutex->lock(200); 
  38.  
  39.   sleep(1); 
  40.  
  41.   if (!$res){ 
  42. //Vevb.com 
  43.     echo "process {$i} unable to lock mutex. /n"; 
  44.  
  45.   }else{ 
  46.  
  47.     echo "process {$i} successfully got the mutex /n"; 
  48.  
  49.     $mutex->unlock(); 
  50.  
  51.   } 
  52.  
  53.   exit(); 
  54.  
  55. } 

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

  1. parent process  
  2.  
  3. parent process  
  4.  
  5. child process 1 is born.  
  6.  
  7. process 1 is getting the mutex  
  8.  
  9. child process 0 is born.  
  10.  
  11. process 0 is getting the mutex  
  12.  
  13. process 1 successfully got the mutex  
  14.  
  15. Child 0 completed 
  16.  
  17. process 0 unable to lock mutex.  
  18.  
  19. 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应用中。

上测试代码:

  1. for($i=0; $i<3; $i++){ 
  2.  
  3.   $pid = pcntl_fork(); 
  4.  
  5.   if($pid <0){ 
  6.  
  7.     die("fork failed"); 
  8.  
  9.   }elseif ($pid>0){ 
  10.  
  11.     //echo "parent process /n"; 
  12.  
  13.   }else{ 
  14.  
  15.     echo "child process {$i} is born. /n"; 
  16.  
  17.     switch ($i) { 
  18.  
  19.     case 0: 
  20.  
  21.       wait(); 
  22.  
  23.       break; 
  24.  
  25.     case 1: 
  26.  
  27.       wait(); 
  28.  
  29.       break; 
  30.  
  31.     case 2: 
  32.  
  33.       sleep(1); 
  34.  
  35.       fire(); 
  36.  
  37.       break; 
  38.  
  39.     } 
  40.  
  41.   } 
  42.  
  43. } 
  44.  
  45. while (pcntl_waitpid(0, $status) != -1) {  
  46.  
  47.   $status = pcntl_wexitstatus($status);  
  48.  
  49.   echo "Child $status completed/n";  
  50.  
  51. } 
  52.  
  53. function wait(){ 
  54.  
  55.   $event = new SyncEvent("UniqueName"); 
  56.  
  57.   echo "before waiting. /n"; 
  58.  
  59.   $event->wait(); 
  60.  
  61.   echo "after waiting. /n"; 
  62.  
  63.   exit(); 
  64.  
  65. } 
  66.  
  67. function fire(){ 
  68.  
  69.   $event = new SyncEvent("UniqueName"); 
  70.  
  71.   $event->fire(); 
  72.  
  73.   exit(); 
  74.  
  75. } 

这里故意少写一个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:除非线程使用了优先级调度机制,否则,线程会被系统调度器去分配,那个线程会第一个锁定互斥量是随机的。

  1. #include<stdlib.h>  
  2.  
  3. #include<stdio.h>  
  4.  
  5. #include<unistd.h>  
  6.  
  7. #include<pthread.h>  
  8.  
  9. typedef struct ct_sum  
  10.  
  11. {  
  12.  
  13.   int sum;  
  14.  
  15.   pthread_mutex_t lock;  
  16.  
  17. }ct_sum;  
  18.  
  19. void * add1(void *cnt)  
  20.  
  21. {     
  22.  
  23.   pthread_mutex_lock(&(((ct_sum*)cnt)->lock));  
  24.  
  25.   for(int i=0; i < 50; i++)  
  26.  
  27.   { 
  28.  
  29.     (*(ct_sum*)cnt).sum += i;    
  30.  
  31.   }  
  32.  
  33.   pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));  
  34.  
  35.   pthread_exit(NULL);  
  36.  
  37.   return 0;  
  38.  
  39. }  
  40.  
  41. void * add2(void *cnt)  
  42.  
  43. {     
  44.  
  45.   pthread_mutex_lock(&(((ct_sum*)cnt)->lock));  
  46.  
  47.   for(int i=50; i<101; i++)  
  48.  
  49.   {   
  50.  
  51.      (*(ct_sum*)cnt).sum += i;   
  52.  
  53.   }  
  54.  
  55.   pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));  
  56.  
  57.   pthread_exit(NULL);  
  58.  
  59.   return 0;  
  60.  
  61. }  
  62.  
  63. int main(void)  
  64.  
  65. { 
  66.  
  67.   pthread_t ptid1, ptid2;  
  68.  
  69.   ct_sum cnt;  
  70.  
  71.   pthread_mutex_init(&(cnt.lock), NULL);  
  72.  
  73.   cnt.sum=0;  
  74.  
  75.   pthread_create(&ptid1, NULL, add1, &cnt);  
  76.  
  77.   pthread_create(&ptid2, NULL, add2, &cnt);  
  78.  
  79.   pthread_join(ptid1,NULL);  
  80.  
  81.   pthread_join(ptid2,NULL); 
  82. //Vevb.com 
  83.   printf("sum %d/n", cnt.sum); 
  84.  
  85.   pthread_mutex_destroy(&(cnt.lock));  
  86.  
  87.   return 0;  
  88.  
  89. } 
  90.  
  91. </pthread.h></unistd.h></stdio.h></stdlib.h> 

信号量

sync模块中的信号量:

SyncSemaphore文档中显示,它和Mutex的不同之处,在于Semaphore一次可以被多个进程(或线程)得到,而Mutex一次只能被一个得到。所以在SyncSemaphore的构造函数中,有一个参数指定信号量可以被多少进程得到。

public SyncSemaphore::__construct ([ string $name [, integer $initialval [, bool $autounlock ]]] ) 就是这个$initialval (initial value)

  1. $lock = new SyncSemaphore("UniqueName", 2); 
  2.  
  3. for($i=0; $i<2; $i++){ 
  4.  
  5.   $pid = pcntl_fork(); 
  6.  
  7.   if($pid <0){ 
  8.  
  9.     die("fork failed"); 
  10.  
  11.   }elseif ($pid>0){ 
  12.  
  13.     echo "parent process /n"; 
  14.  
  15.   }else{ 
  16.  
  17.     echo "child process {$i} is born. /n"; 
  18.  
  19.     obtainLock($lock, $i); 
  20.  
  21.   } 
  22.  
  23. } 
  24.  
  25. while (pcntl_waitpid(0, $status) != -1) {  
  26.  
  27.   $status = pcntl_wexitstatus($status);  
  28.  
  29.   echo "Child $status completed/n";  
  30.  
  31. } 
  32.  
  33. function obtainLock ($lock, $i){ 
  34.  
  35.   echo "process {$i} is getting the lock /n"; 
  36.  
  37.   $res = $lock->lock(200); 
  38.  
  39.   sleep(1); 
  40.  
  41.   if (!$res){ 
  42.  
  43.     echo "process {$i} unable to lock lock. /n"; 
  44.  
  45.   }else{ 
  46.  
  47.     echo "process {$i} successfully got the lock /n"; 
  48.  
  49.     $lock->unlock(); 
  50.  
  51.   } 
  52.  
  53.   exit(); 
  54.  
  55. } 

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

sysvsem模块中的信号量

sem_get 创建信号量

sem_remove 删除信号量(一般不用)

sem_acquire 请求得到信号量

sem_release 释放信号量。和 sem_acquire 成对使用。

  1. $key = ftok('/tmp', 'c'); 
  2.  
  3. $sem = sem_get($key); 
  4.  
  5. for($i=0; $i<2; $i++){ 
  6.  
  7.   $pid = pcntl_fork(); 
  8.  
  9.   if($pid <0){ 
  10.  
  11.     die("fork failed"); 
  12.  
  13.   }elseif ($pid>0){ 
  14.  
  15.     //echo "parent process /n"; 
  16.  
  17.   }else{ 
  18.  
  19.     echo "child process {$i} is born. /n"; 
  20.  
  21.     obtainLock($sem, $i); 
  22.  
  23.   } 
  24.  
  25. } 
  26.  
  27. while (pcntl_waitpid(0, $status) != -1) {  
  28.  
  29.   $status = pcntl_wexitstatus($status);  
  30.  
  31.   echo "Child $status completed/n";  
  32.  
  33. } 
  34.  
  35. sem_remove($sem); // finally remove the sem 
  36.  
  37. function obtainLock ($sem, $i){ 
  38.  
  39.   echo "process {$i} is getting the sem /n"; 
  40.  
  41.   $res = sem_acquire($sem, true); 
  42.  
  43.   sleep(1); 
  44.  
  45.   if (!$res){ 
  46.  
  47.     echo "process {$i} unable to get sem. /n"; 
  48.  
  49.   }else{ 
  50.  
  51.     echo "process {$i} successfully got the sem /n"; 
  52.  
  53.     sem_release($sem); 
  54.  
  55.   } 
  56.  
  57.   exit(); 
  58.  
  59. } 

这里有一个问题,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。

输出为:

  1. parent process  
  2.  
  3. parent process  
  4.  
  5. child process 1 is born.  
  6.  
  7. process 1 is getting the mutex  
  8.  
  9. child process 0 is born.  
  10.  
  11. process 0 is getting the mutex  
  12.  
  13. process 1 successfully got the mutex  
  14.  
  15. Child 0 completed 
  16.  
  17. process 0 unable to lock mutex.  
  18.  
  19. Child 0 completed 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表