我在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()函数值:
....Really不知道原因。请帮帮忙。
发布于 2013-06-25 14:37:47
静态变量不在上下文之间共享,原因是静态变量有一个类条目作用域,而处理程序用于管理对象作用域。
当一个新线程启动时,statics会被复制(移除复杂的变量,比如对象和资源)。
静态作用域可以被认为是一种线程本地存储。
此外,如果成员不是静态的.从pthread定义派生的类的所有成员都被认为是公共的。
我鼓励您阅读与pthread一起分发的示例,它们也可以在github上找到。
发布于 2013-06-24 19:50:31
你是如何实现多线程的?
PHP不具有与Java等语言相同的线程支持,在Java中,您有一个不断运行在应用程序级别的JVM。
使用PHP,每个页面请求都会创建一个新的PHP实例来处理该请求,并且静态变量的作用域仅针对每个正在运行的实例。
要在线程之间共享数据,您需要将值存储在DB、会话或一个简单的文件中,具体取决于您的需求。
https://stackoverflow.com/questions/17274011
复制相似问题