PHP의 다른 스레드간에 정적 변수를 공유하는 데 문제가 있습니다. 간단히 말해서 나는 을 원한다. 하나의 스레드에 정적 변수를 작성한다. 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();
?>
예상 출력은 런 모드() 방법 : 런 100
모드() 메소드 : 정적 변수 입력 모드 w_mode() funcion W 값 R 입력 모드 r_mode 정적 변수() 함수 값 : 런타임 100
모드() 메소드 정적 변수 R 입력 모드 r_mode() 함수 값 : 100
,451,515,그러나 실제로 나는 같은 출력, 실행에 모드() 메소드를 얻고있다 : 실행 100
모드() 메소드 : R 입력 모드 입력 모드 w_mode() funcion 정적 변수의 값 W r_mode() 함수 정적 변수 값 : 런
모드()에있어서 R 정적 변수 입력 모드 r_mode() 함수 값 : 원인 정말로 모르고
..... 도와주세요.
안녕하세요 폴 S입니다. 친절한 답변과 시간을 보내 주셔서 감사합니다. 내 불완전한 질문에 대해 죄송합니다. 요청에서 2 개의 스레드를 시작하려고합니다. 감사 Vinay – user2515938
http : // php.net/Thread –