一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - PHP教程 - PHP程序中的文件鎖、互斥鎖、讀寫鎖使用技巧解析

PHP程序中的文件鎖、互斥鎖、讀寫鎖使用技巧解析

2021-01-03 17:14一堆好人卡 PHP教程

這篇文章主要介紹了PHP程序中的文件鎖、互斥鎖、讀寫鎖使用技巧解析,其中重點講解了sync模塊和pthreads模塊中的使用實例,需要的朋友可以參考下

文件鎖
全名叫 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
2
3
4
5
6
7
8
9
10
11
12
13
14
$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異常丑陋,請無視。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
$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

?
1
2
3
4
5
6
7
8
9
10
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

這里子進程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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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模塊
鎖定和解鎖互斥量:

函數:

?
1
2
3
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#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;
}

信號量
sync模塊中的信號量:

SyncSemaphore文檔中顯示,它和Mutex的不同之處,在于Semaphore一次可以被多個進程(或線程)得到,而Mutex一次只能被一個得到。所以在SyncSemaphore的構造函數中,有一個參數指定信號量可以被多少進程得到。
public SyncSemaphore::__construct ([ string $name [, integer $initialval [, bool $autounlock ]]] ) 就是這個$initialval (initial value)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
$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 成對使用。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
$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();
}

這里有一個問題,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
2
3
4
5
6
7
8
9
10
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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 天堂久久久久va久久久久 | 五月婷婷俺也去开心 | 亚洲天堂99 | 亚洲www美色 | 肉宠文很肉到处做1v1 | 美女扒开腿让男人桶爽动态图片 | 欧美腐剧mm在线观看 | japanesexxxx在线播放| 91精品手机国产在线观 | 国产二区视频在线观看 | 亚洲国产成人精品无码区99 | 特a级片 | 精品国产日韩一区三区 | 99精品国产自在现线观看 | 满溢游泳池免费土豪全集下拉版 | 成人性生交小说免费看 | xx18美女美国 | 欧美成人中文字幕 | 国产视频二区 | 二次元美女互摸隐私互扒 | 日韩成人免费 | 国产精品视频免费视频 | 我要色色网 | 日韩拍拍拍 | 草莓视频在线免费观看 | 插入逼 | 国产裸舞在线一区二区 | 香蕉免费一区二区三区 | 99re这里只有精品视频在线观看 | 男人天堂色男人 | 91亚洲专区 | 亚洲高清中文字幕 | 武侠艳妇屈辱的张开双腿 | 69pao强力打造免费高速 | 欧美生活一级片 | 日本96在线精品视频免费观看 | 失禁尿丝袜vk | 美女黑人做受xxxxxⅹ | 精品视频 九九九 | ysl千人千色t9t9t9 | 高肉h护士办公室play |