《PHP教程:PHP程序中的文件鎖、互斥鎖、讀寫鎖使用技巧解析》要點(diǎn):
本文介紹了PHP教程:PHP程序中的文件鎖、互斥鎖、讀寫鎖使用技巧解析,希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP實(shí)例文件鎖
全名叫 advisory file lock, 書中有提及. 這類鎖比較常見,例如 mysql, php-fpm 啟動(dòng)之后都會有一個(gè)pid文件記錄了進(jìn)程id,這個(gè)文件就是文件鎖.
PHP實(shí)例這個(gè)鎖可以防止重復(fù)運(yùn)行一個(gè)進(jìn)程,例如在使用crontab時(shí),限定每一分鐘執(zhí)行一個(gè)任務(wù),但這個(gè)進(jìn)程運(yùn)行時(shí)間可能超過一分鐘,如果不用進(jìn)程鎖解決沖突的話兩個(gè)進(jìn)程一起執(zhí)行就會有問題.
PHP實(shí)例使用PID文件鎖還有一個(gè)好處,方便進(jìn)程向自己發(fā)停止或者重啟信號.例如重啟php-fpm的命令為
PHP實(shí)例kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`
發(fā)送USR2信號給pid文件記錄的進(jìn)程,信號屬于進(jìn)程通信,會另開一個(gè)篇幅.
PHP實(shí)例php的接口為flock,文檔比較詳細(xì).先看一下定義,bool flock ( resource $handle , int $operation [, int &$wouldblock ] ).
PHP實(shí)例需要注意的是,這個(gè)函數(shù)默認(rèn)是阻塞的,如果想非阻塞可以在 operation 加一個(gè) bitmask LOCK_NB. 接下來測試一下.
PHP實(shí)例
$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);
PHP實(shí)例保存為 process.php,運(yùn)行php process.php &, 此時(shí)再次運(yùn)行php process.php,就可以看到錯(cuò)誤提示.flock也有共享鎖,LOCK_SH.
PHP實(shí)例互斥鎖和讀寫鎖
sync模塊中的Mutex:
Mutex是一個(gè)組合詞,mutual exclusion.用pecl安裝一下sync模塊, pecl install sync. 文檔中的SyncMutex只有兩個(gè)方法,lock 和 unlock, 我們就直接上代碼測試吧.沒有用IDE寫,所以cs異常丑陋,請無視.
PHP實(shí)例
$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();
}
PHP實(shí)例保存為mutex.php, run php mutex.php, output is
PHP實(shí)例
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 completed
process 0 unable to lock mutex.
Child 0 completed
PHP實(shí)例這里子進(jìn)程0和1不一定誰在前面.但是總有一個(gè)得不到鎖.這里SyncMutex::lock(int $millisecond)的參數(shù)是 millisecond, 代表阻塞的時(shí)長, -1 為無限阻塞.
PHP實(shí)例sync模塊中的讀寫鎖:
SyncReaderWriter的方法類似,readlock, readunlock, writelock, writeunlock,成對出現(xiàn)即可,沒有寫測試代碼,應(yīng)該和Mutex的代碼一致,把鎖替換一下就可以.
PHP實(shí)例sync模塊中的Event:
感覺和golang中的Cond比較像,wait()阻塞,fire()喚醒Event阻塞的一個(gè)進(jìn)程.有一篇好文介紹了Cond, 可以看出Cond就是鎖的一種固定用法.SyncEvent也一樣.
php文檔中的例子顯示,fire()方法貌似可以用在web應(yīng)用中.
PHP實(shí)例上測試代碼
PHP實(shí)例
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();
}
PHP實(shí)例這里故意少寫一個(gè)fire(), 所以程序會阻塞,證明了 fire() 一次只喚醒一個(gè)進(jìn)程.
PHP實(shí)例pthreads模塊
鎖定和解鎖互斥量:
PHP實(shí)例函數(shù):
PHP實(shí)例
pthread_mutex_lock (mutex)
pthread_mutex_trylock (mutex)
pthread_mutex_unlock (mutex)
PHP實(shí)例用法:
PHP實(shí)例線程用pthread_mutex_lock()函數(shù)去鎖定指定的mutex變量,若該mutex已經(jīng)被另外一個(gè)線程鎖定了,該調(diào)用將會阻塞線程直到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().
PHP實(shí)例 嘗試著去鎖定一個(gè)互斥量,然而,若互斥量已被鎖定,程序會立刻返回并返回一個(gè)忙錯(cuò)誤值.該函數(shù)在優(yōu)先級改變情況下阻止死鎖是非常有用的.線程可以用pthread_mutex_unlock()解鎖自己占用的互斥量.在一個(gè)線程完成對保護(hù)數(shù)據(jù)的使用,而其它線程要獲得互斥量在保護(hù)數(shù)據(jù)上工作時(shí),可以調(diào)用該函數(shù).若有一下情形則會發(fā)生錯(cuò)誤:
PHP實(shí)例互斥量并沒有多么“神奇”的,實(shí)際上,它們就是參與的線程的“君子約定”.寫代碼時(shí)要確信正確地鎖定,解鎖互斥量.
PHP實(shí)例Q:有多個(gè)線程等待同一個(gè)鎖定的互斥量,當(dāng)互斥量被解鎖后,那個(gè)線程會第一個(gè)鎖定互斥量?
A:除非線程使用了優(yōu)先級調(diào)度機(jī)制,否則,線程會被系統(tǒng)調(diào)度器去分配,那個(gè)線程會第一個(gè)鎖定互斥量是隨機(jī)的.
PHP實(shí)例
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
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;
}
PHP實(shí)例信號量
sync模塊中的信號量:
SyncSemaphore文檔中顯示,它和Mutex的不同之處,在于Semaphore一次可以被多個(gè)進(jìn)程(或線程)得到,而Mutex一次只能被一個(gè)得到.所以在SyncSemaphore的構(gòu)造函數(shù)中,有一個(gè)參數(shù)指定信號量可以被多少進(jìn)程得到.
public SyncSemaphore::__construct ([ string $name [, integer $initialval [, bool $autounlock ]]] ) 就是這個(gè)$initialval (initial value)
PHP實(shí)例
$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();
}
PHP實(shí)例這時(shí)候兩個(gè)進(jìn)程都能得到鎖.
PHP實(shí)例
$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 sem
function 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();
}
PHP實(shí)例這里有一個(gè)問題,sem_acquire()第二個(gè)參數(shù)$nowait默認(rèn)為false,阻塞.我設(shè)為了true,如果得到鎖失敗,那么后面的sem_release會報(bào)警告 PHP Warning:? sem_release(): SysV semaphore 4 (key 0x63000081) is not currently acquired in /home/jason/sysvsem.php on line 33, 所以這里的release操作必須放在得到鎖的情況下執(zhí)行,前面的幾個(gè)例子中沒有這個(gè)問題,沒得到鎖執(zhí)行release也不會報(bào)錯(cuò).當(dāng)然最好還是成對出現(xiàn),確保得到鎖的情況下再release.
此外,ftok這個(gè)方法的參數(shù)有必要說明下,第一個(gè) 必須是existing, accessable的文件, 一般使用項(xiàng)目中的文件,第二個(gè)是單字符字符串.返回一個(gè)int.
PHP實(shí)例輸出為
PHP實(shí)例
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 completed
process 0 unable to lock mutex.
Child 0 completed
維易PHP培訓(xùn)學(xué)院每天發(fā)布《PHP教程:PHP程序中的文件鎖、互斥鎖、讀寫鎖使用技巧解析》等實(shí)戰(zhàn)技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培養(yǎng)人才。
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/7278.html