2013-06-24 99 views
4

我在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()函數 值靜態變量:

....真的不知道原因。請幫忙。

回答

-3

你是如何完成多線程的?

PHP不像Java這樣的語言具有相同的線程支持,其中有一個JVM,它在應用程序級別上不斷運行。

使用PHP,每個頁面請求正在創建一個新的PHP實例來處理該請求,並且靜態變量的作用域僅針對每個正在運行的實例。

要在線程之間共享數據,您需要根據需要將值存儲在數據庫,會話或簡單文件中。

+0

你好Paul S,謝謝你的好評和你的時間。對不起,我的問題不完整。我打算在請求中啓動2個線程。感謝Vinay – user2515938

+0

http:// php。網絡/線程 –

7

靜態變量不在上下文之間共享,原因是靜態變量具有類入口範圍,處理程序用於管理對象範圍。

當一個新線程啓動時,靜態被複制(除去複雜變量,如對象和資源)。

靜態範圍可以被認爲是一種線程本地存儲。

此外,成員不是靜態的...從pthreads定義派生的類的所有成員都被認爲是公共的。

我鼓勵您閱讀使用pthreads發佈的示例,它們也可以在github上獲得。

+0

親愛的喬,謝謝你的答案。我也經過幾次嘗試後認爲範圍是原因。謝謝Vinay – user2515938