PHP默认情况没有开启功能,要支持该功能在编译PHP的时候要加入下面几个选项 System V消息,--enable-sysvmsg System V信号量支持,--enable-sysvsem System V共享内存支持,--enable-sysvshm
PHP还挺shmop共享内存,在编译的时候开启 --enable-shmop
System V共享内存的相关函数:
1: 创建信号量唯一标识符
$ftok = ftok(__FILE__, 'a');
2: 创建共享内存端
$id = shm_attach ( $ftok, 1000 , 0666 )
3: 断开与共享内存段的连接
shm_detach ( $id )
4: 获取一个变量值
$val = shm_get_var ( $id , $key )
5: 检测变量是否存在
shm_has_var ( $id , $key )
6: 添加一个值到共享内存里
shm_put_var ( $id , $key , $val )
7: 从共享内存中删除一个变量
shm_remove_var ( $id , $key
)
8: 从系统中删除共享内存
shm_remove ( $id)
<?php $tmp = tempnam(__FILE__, 'PHP'); $key = ftok($tmp, 'a'); $shmid = shm_attach($key); $counter = 0; shm_put_var( $shmid, 1, $counter ); class CounterThread extends Thread { public $shmid; public $is_runing = true; public function __construct($shmid){ $this->shmid = $shmid; } public function run() { $counter = shm_get_var( $this->shmid, 1 ); $counter++; shm_put_var( $this->shmid, 1, $counter ); printf("Thread #%lu says: %s\n", $this->getThreadId(),$counter); } } for ($i=0;$i<10;$i++){ $threads[] = new CounterThread($shmid); } for ($i=0;$i<10;$i++){ $threads[$i]->start(); } for ($i=0;$i<10;$i++){ $threads[$i]->join(); } shm_remove( $shmid ); shm_detach( $shmid );