
文章插圖
說(shuō)明
1、信號(hào)量:是系統(tǒng)提供的一種原子操作,一個(gè)信號(hào)數(shù)量,同時(shí)只有一個(gè)進(jìn)程能操作 。
一個(gè)過(guò)程獲得一個(gè)信號(hào),必須被過(guò)程釋放 。
2、共享內(nèi)存:是系統(tǒng)在存儲(chǔ)器中打開的一個(gè)公共存儲(chǔ)器區(qū)域,任何一個(gè)過(guò)程都可以訪問(wèn) 。
在同一時(shí)刻,可以有多個(gè)過(guò)程訪問(wèn)該區(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: 0n";}// 用完釋放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)存的介紹,希望對(duì)大家有所幫助 。
以上關(guān)于本文的內(nèi)容,僅作參考!溫馨提示:如遇健康、疾病相關(guān)的問(wèn)題,請(qǐng)您及時(shí)就醫(yī)或請(qǐng)專業(yè)人士給予相關(guān)指導(dǎo)!
「愛刨根生活網(wǎng)」www.malaban59.cn小編還為您精選了以下內(nèi)容,希望對(duì)您有所幫助:- tcp和udp的特點(diǎn)和區(qū)別 php中TCP和UDP的區(qū)別
- php psr規(guī)范 php PSR-4是什么意思
- hash加密算法有哪些 php Mhash算法的加密
- php用遞歸求n的階乘 php中n階乘的實(shí)現(xiàn)方法
- php垃圾收集機(jī)制怎么樣的 php引用計(jì)數(shù)如何實(shí)現(xiàn)垃圾回收
- php require和include區(qū)別 php中require和include如何區(qū)分
- cookie加密方式 php中如何配置Cookie加密
- php 消息隊(duì)列 php消息隊(duì)列的介紹
- php zval PHP中Zval是什么
- php中Suhosin是什么
