我在PHP中的不同線程之間共享靜態變量時遇到問題。 簡單地說,我想 1.在一個線程中寫入一個靜態變量 2.在其他線程中讀取它並執行所需的過程並清理它。 爲了測試上面的要求,我寫了下面的PHP腳本。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()funcion 值靜態變量:100
模式run()方法:R t 輸入模式r_mode ()函數 值靜態變量的:在運行100
模式()方法:R t 輸入模式r_mode()函數 值靜態變量:100
但實際上我正在輸出, 模式run()方法:W 輸入模式w_mode()funcion 值靜態變量的:在運行100
模式()方法:R t 輸入模式r_mode()函數 值靜態變量:
模式run()方法:R t 輸入模式r_mode()函數 值靜態變量:
....真的不知道原因。請幫忙。
你好Paul S,謝謝你的好評和你的時間。對不起,我的問題不完整。我打算在請求中啓動2個線程。感謝Vinay – user2515938
http:// php。網絡/線程 –