代码之家  ›  专栏  ›  技术社区  ›  Amir Rasti

使用静态类成员作为超全局变量的php线程安全性

  •  0
  • Amir Rasti  · 技术社区  · 6 年前

    我想让我自己的超全局变量可以从我的所有脚本访问,我使用静态类成员来实现这一点,但我担心的是,当php服务器为每个脚本文件创建一个单独的线程时,在我的一些脚本中,我正在读写或修改这些变量,我的代码的关键部分应该用互斥锁来保护锁?

    用法示例

    class MySuperGlobals {
          public static $Variables=array("visited"=>array());
    
         }
    

    索引.php

    <?php
    
       include "SuperGlobals.php";
       array_push(MySuperGlobals::$Variables["visited"] ,"index");
       echo MySuperGlobals::$Variables["visited"][count(MySuperGlobals::$Variables["visited"])-1];//last element
    
    ?>
    

    页面1.php

    <?php
        include "SuperGlobals.php";
        array_push(MySuperGlobals::$Variables["visited"] ,"page1");
        echo MySuperGlobals::$Variables["visited"][count(MySuperGlobals::$Variables["visited"])-1];//last element
    ?>
    

    在上面的示例中,对于静态成员(忽略echo),array\u push-alone是线程安全的,那么整个push和echo呢?如果我们想保护它,应该怎么做?我应该在类中创建一个静态互斥对象并锁定和解锁这些行吗?

    0 回复  |  直到 6 年前