有些时候我们希望在多个线程中共享一些需要的数据,我们可以使用shmop扩展。
class Count extends Thread {
private $name = '';
public function __construct($name) {
$this->name = $name;
}
public function run() {
//在Linux下可以使用sysvshm的扩展,shm_等函数
//共享内存段的key
$shmKey = 123;
//创建共享内存段
$shmId = shmop_open($shmKey,'c',0777,64);
//读取共享内存数据
$data = trim(shmop_read($shmId,64));
$data = intval($data);
++$data;
shmop_write($shmId,$data,0);
echo "thread {$this->name} data {$data} \r\n";
//删除关闭共享内存段
shmop_delete($shmId);
shmop_close($shmId);
}
}
$threads = array();
for($ix = 0; $ix < 10; ++$ix) {
$thread = new Count($ix);
$thread->start();
$threads[] = $thread;
}
foreach($threads as $thread) {
$thread->join();
}
如上代码可以正常运行。结果如下:
但是如果我把代码改成如下情况:
class Count extends Thread {
private $name = '';
private $shmId = '';
public function __construct($name,$shmId) {
$this->name = $name;
$this->shmId = $shmId;
}
public function run() {
$data = shmop_read($this->shmId,64);
$data = intval($data);
++$data;
shmop_write($this->shmId,0);
echo "thread {$this->name} data {$data} \r\n";
}
}
//在Linux下可以使用sysvshm的扩展
//共享内存段的key
$shmKey = 123;
//创建共享内存段
$shmId = shmop_open($shmKey,64);
//写入数据到共享内存段
shmop_write($shmId,'1',0);
$threads = array();
for($ix = 0; $ix < 10; ++$ix) {
$thread = new Count($ix,$shmId);
$thread->start();
$threads[] = $thread;
}
foreach($threads as $thread) {
$thread->join();
}
echo shmop_read($shmId,64);
//删除关闭共享内存段
shmop_delete($shmId);
shmop_close($shmId);
上述代码就会出现如下警告:
Warning: shmop_read(): no shared memory segment with an id of [4] in D:\wwwroot\
thread\demo6.PHP on line 13
PHP Warning: shmop_write(): no shared memory segment with an id of [4] in D:\ww
wroot\thread\demo6.PHP on line 16
字面意思是无共享内存段,在new线程的过程中我们已经通过构造函数把$shmId传进去了,为什么会出现无共享内存段?
我们知道shmop_open函数成功创建共享内存段后会返回一个ID,该类型是int型。当我们把该ID传入到子线程中时,子线程是无法通过该ID找到共享内存段。