溫馨提示×

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

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

php信號(hào)量和共享內(nèi)存有什么用

發(fā)布時(shí)間:2021-06-21 10:46:25 來(lái)源:億速云 閱讀:138 作者:chen 欄目:編程語(yǔ)言

這篇文章主要講解了“php信號(hào)量和共享內(nèi)存有什么用”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“php信號(hào)量和共享內(nèi)存有什么用”吧!

說(shuō)明

1、信號(hào)量:是系統(tǒng)提供的一種原子操作,一個(gè)信號(hào)數(shù)量,同時(shí)只有一個(gè)進(jìn)程能操作。一個(gè)過程獲得一個(gè)信號(hào),必須被過程釋放。

2、共享內(nèi)存:是系統(tǒng)在存儲(chǔ)器中打開的一個(gè)公共存儲(chǔ)器區(qū)域,任何一個(gè)過程都可以訪問,在同一時(shí)刻,可以有多個(gè)過程訪問該區(qū)域,為了保證數(shù)據(jù)的一致性,需要對(duì)該存儲(chǔ)器區(qū)域進(jìn)行鎖定或信號(hào)。

實(shí)例

echo "parent progress pid:{$parentPid}\n";
$childList = array();
 
// 創(chuàng)建共享內(nèi)存,創(chuàng)建信號(hào)量,定義共享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++) {
        // 獲得信號(hào)量
        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{
            // 無(wú)值,初始化
            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個(gè)寫進(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)存與信號(hào)量
shm_remove($shareMemory);
sem_remove($signal);
echo "({$parentPid})main progress end!\n";

感謝各位的閱讀,以上就是“php信號(hào)量和共享內(nèi)存有什么用”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)php信號(hào)量和共享內(nèi)存有什么用這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

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

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

php
AI