<?php
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, 0, 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();
}
如上代碼能夠正常運行。結果以下:
<?php
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, 0, 64);
$data = intval($data);
++$data;
shmop_write($this->shmId, $data, 0);
echo "thread {$this->name} data {$data} \r\n";
}
}
//在Linux下能夠使用sysvshm的擴展
//共享內存段的key
$shmKey = 123;
//建立共享內存段
$shmId = shmop_open($shmKey, 'c', 0777, 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, 0, 64);
//刪除關閉共享內存段
shmop_delete($shmId);
shmop_close($shmId);