PHP:在线程之间共享静态变量
发布时间:2020-12-13 16:51:22 所属栏目:PHP教程 来源:网络整理
导读:我在 PHP中的不同线程之间共享静态变量时遇到问题. 简单来说,我想 1.在一个线程中写一个静态变量 2.在其他线程中读取它并执行所需的过程并清理它. 为了测试上面的要求,我在下面写了PHP脚本. ?phpclass ThreadDemo1 extends Thread{private $mode; //to run 2
我在
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()方法中的模式:R run()方法中的模式:R 但实际上我得到的输出为, run()方法中的模式:R run()方法中的模式:R ….真的没有意识到原因.请帮忙. 解决方法
静态变量不在上下文之间共享,原因是静态变量具有类入口范围,处理程序用于管理对象范围.
启动新线程时,将复制静态(删除复杂变量,如对象和资源). 静态范围可以被认为是一种线程本地存储. 此外,在成员不是静态的情况下……派生自pthreads定义的类的所有成员都被视为公共成员. 我鼓励您阅读使用pthread分发的示例,它们也可以在github上找到. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |