【问题标题】:PHP: Sharing a static variable between threadsPHP:在线程之间共享一个静态变量
【发布时间】:2013-06-20 20:57:44
【问题描述】:

我在 PHP 的不同线程之间共享静态变量时遇到问题。 简而言之,我想 1.在一个线程中写一个静态变量 2.在其他线程中读取它并执行所需的过程并对其进行清理。 为了测试上述要求,我在 PHP 脚本下面编写了。

<?php

class ThreadDemo1 extends Thread
{
private $mode;  //to run 2 threads in different modes
private static $test;  //Static variable shared between threads

//Instance is created with different mode
function __construct($mode) {
    $this->mode = $mode;            
}

//Set the static variable using mode 'w'
function w_mode() {
   echo 'entered mode w_mode() funcion';
   echo "<br />";

   //Set shared variable to 0 from initial 100
   self::$test = 100;

   echo "Value of static variable : ".self::$test;
   echo "<br />";
   echo "<br />";

   //sleep for a while
   sleep(1);

}

//Read the staic vaiable set in mode 'W'
function r_mode() {
   echo 'entered mode r_mode() function';
   echo "<br />";

   //printing the staic variable set in W mode
   echo "Value of static variable : ".self::$test;
   echo "<br />";
   echo "<br />";

   //Sleep for a while
   sleep(2);

}

//Start the thread in different modes
public function run() {

//Print the mode for reference
echo "Mode in run() method: ".$this->mode;
echo "<br />";

    switch ($this->mode)
    {

    case 'W':
          $this->w_mode();
          break;

   case 'R':
         $this->r_mode();
         break;

  default:
        echo "Invalid option";        

        }      
    }
}


$trd1 = new ThreadDemo1('W');
$trd2 = new ThreadDemo1('R');
$trd3 = new ThreadDemo1('R');
$trd1->start();
$trd2->start();
$trd3->start();
?>

预期的输出是, run() 方法中的模式:W 进入模式 w_mode() 函数 静态变量值:100

run() 方法中的模式:R 进入模式 r_mode() 函数 静态变量的值:100

run() 方法中的模式:R 进入模式 r_mode() 函数 静态变量值:100

但实际上我得到的输出是, run() 方法中的模式:W 进入模式 w_mode() 函数 静态变量值:100

run() 方法中的模式:R 进入模式 r_mode() 函数 静态变量的值:

run() 方法中的模式:R 进入模式 r_mode() 函数 静态变量的值:

....真的不知道原因。请帮忙。

【问题讨论】:

    标签: php multithreading static-variables


    【解决方案1】:

    静态变量在上下文之间不共享,原因是静态变量有一个类入口作用域,而handlers是用来管理对象作用域的。

    当一个新线程启动时,会复制静态数据(删除复杂变量,如对象和资源)。

    静态作用域可以被认为是一种线程本地存储。

    此外,如果成员不是静态的......从 pthread 定义派生的类的所有成员都被认为是公共的。

    我鼓励您阅读使用 pthread 分发的示例,它们也可以在 github 上找到。

    【讨论】:

    • 亲爱的乔,感谢您的回答。我也在几次尝试后得出结论,因为范围是原因。谢谢 Vinay
    【解决方案2】:

    你是如何实现多线程的?

    PHP 不像 Java 这样的语言具有相同的线程支持,在 Java 中你有一个在应用程序级别持续运行的 JVM。

    使用 PHP,每个页面请求都会创建一个新的 PHP 实例来处理该请求,并且静态变量的范围仅适用于每个正在运行的实例。

    要在线程之间共享数据,您需要根据需要将值存储在数据库、会话或简单文件中。

    【讨论】:

    • 您好 Paul S,感谢您的友好回答和您的宝贵时间。抱歉我的问题不完整。我打算在请求中启动 2 个线程。谢谢维奈
    猜你喜欢
    • 2011-06-23
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多