php Pthread 多線程 (四) 共享內存

有些時候咱們但願在多個線程中共享一些須要的數據,咱們能夠使用shmop擴展。
<?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 Pthread 多線程 (四) 共享內存 - 懷素真 - 因上努力 果上隨緣
 
可是若是我把代碼改爲以下狀況:
<?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);
上述代碼就會出現以下警告:
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找到共享內存段。
相關文章
相關標籤/搜索