zoukankan      html  css  js  c++  java
  • 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} 
    ";
    
            //删除关闭共享内存段
            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} 
    ";
        }
    }
    
    //在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
    threaddemo6.php on line 13
    PHP Warning: shmop_write(): no shared memory segment with an id of [4] in D:ww
    wroot	hreaddemo6.php on line 16
    
    字面意思是无共享内存段,在new线程的过程中我们已经通过构造函数把$shmId传进去了,为什么会出现无共享内存段?
    我们知道shmop_open函数成功创建共享内存段后会返回一个ID,该类型是int型。当我们把该ID传入到子线程中时,子线程是无法通过该ID找到共享内存段。
     
  • 相关阅读:
    秋风下的萧瑟 NOIP2018 游记
    Dsu on Tree
    BZOJ 3812 : 主旋律
    FFT&NTT
    manacher
    Winniechen’s test1
    如何在万亿级别规模的数据量上使用Spark
    Spark运行时的内核架构以及架构思考
    hadoop离线数据存储和挖掘架构
    Hadoop平台的基本组成与生态系统
  • 原文地址:https://www.cnblogs.com/jkko123/p/6294594.html
Copyright © 2011-2022 走看看