溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

php信號量和共享內(nèi)存的概念是什么

發(fā)布時間:2022-05-12 14:27:42 來源:億速云 閱讀:118 作者:iii 欄目:大數(shù)據(jù)

本文小編為大家詳細(xì)介紹“php信號量和共享內(nèi)存的概念是什么”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“php信號量和共享內(nèi)存的概念是什么”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。

說明

1、信號量:是系統(tǒng)提供的一種原子操作,一個信號數(shù)量,同時只有一個進(jìn)程能操作。

一個過程獲得一個信號,必須被過程釋放。

2、共享內(nèi)存:是系統(tǒng)在存儲器中打開的一個公共存儲器區(qū)域,任何一個過程都可以訪問。

在同一時刻,可以有多個過程訪問該區(qū)域,為了保證數(shù)據(jù)的一致性,需要對該存儲器區(qū)域進(jìn)行鎖定或信號。

實例

echo "parent progress pid:{$parentPid}\n";
$childList = array();
 
// 創(chuàng)建共享內(nèi)存,創(chuàng)建信號量,定義共享key
$shm_id = ftok(__FILE__,'m');
$sem_id = ftok(__FILE__,'s');
$shareMemory = shm_attach($shm_id);
$signal = sem_get($sem_id);
const SHARE_KEY = 1;
// 生產(chǎn)者
function producer(){
    global $shareMemory;
    global $signal;
    $pid = posix_getpid();
    $repeatNum = 5;
    for ( $i = 1; $i <= $repeatNum; $i++) {
        // 獲得信號量
        sem_acquire($signal);
        
        if (shm_has_var($shareMemory,SHARE_KEY)){
            // 有值,加一
            $count = shm_get_var($shareMemory,SHARE_KEY);
            $count ++;
            shm_put_var($shareMemory,SHARE_KEY,$count);
            echo "({$pid}) count: {$count}\n";
        }else{
            // 無值,初始化
            shm_put_var($shareMemory,SHARE_KEY,0);
            echo "({$pid}) count: 0\n";
        }
        // 用完釋放
        sem_release($signal);
        
        $rand = rand(1,3);
        sleep($rand);
    }
}
function createProgress($callback){
    $pid = pcntl_fork();
    if ( $pid == -1) {
        // 創(chuàng)建失敗
        exit("fork progress error!\n");
    } else if ($pid == 0) {
        // 子進(jìn)程執(zhí)行程序
        $pid = posix_getpid();
        $callback();
        exit("({$pid})child progress end!\n");
    }else{
        // 父進(jìn)程執(zhí)行程序
        return $pid;
    }
}
// 3個寫進(jìn)程
for ($i = 0; $i < 3; $i ++ ) {
    $pid = createProgress('producer');
    $childList[$pid] = 1;
    echo "create producer child progress: {$pid} \n";
}
// 等待所有子進(jìn)程結(jié)束
while(!empty($childList)){
    $childPid = pcntl_wait($status);
    if ($childPid > 0){
        unset($childList[$childPid]);
    }
}
// 釋放共享內(nèi)存與信號量
shm_remove($shareMemory);
sem_remove($signal);
echo "({$parentPid})main progress end!\n";

讀到這里,這篇“php信號量和共享內(nèi)存的概念是什么”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI