本文实例讲述了php进程(线程)通信基础之System V共享内存。分享给大家供大家参考,具体如下:
PHP默认情况没有开启功能,要支持该功能在编译PHP的时候要加入下面几个选项 System V消息,--enable-sysvmsg System V信号量支持,--enable-sysvsem System V共享内存支持,--enable-sysvshm
PHP还挺shmop共享内存,在编译的时候开启 --enable-shmop
System V共享内存的相关函数:
1: 创建信号量唯一标识符
1
|
$ftok = ftok ( __FILE__ , 'a' ); |
2: 创建共享内存端
1
|
$id = shm_attach ( $ftok , 1000 , 0666 ) |
3: 断开与共享内存段的连接
1
|
shm_detach ( $id ) |
4: 获取一个变量值
1
|
$val = shm_get_var ( $id , $key ) |
5: 检测变量是否存在
1
|
shm_has_var ( $id , $key ) |
6: 添加一个值到共享内存里
1
|
shm_put_var ( $id , $key , $val ) |
7: 从共享内存中删除一个变量
1
|
shm_remove_var ( $id , $key ) |
8: 从系统中删除共享内存
1
|
shm_remove ( $id ) |
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
|
<?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 ); |
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://www.cnblogs.com/zz-952/p/9766189.html