我有以下PHP代码:
<?php
class StackableAr extends Stackable{
public function run(){}
}
class MyThread1 extends Thread{
public $settings;
public function __construct($settings){
$this->settings = $settings;
}
public function run(){
print "thread1: start\n";
for($n = 0; $n < 8; $n++){
print "thread1: $n\n";
if($n == 2){
print_r($this->settings);
}
elseif($n == 4){
$this->settings['test2'] = new StackableAr();
$this->settings['test2']['attr2'] = 'string2';
$this->settings['test3'] = 'string3';
}
elseif($n == 6){
print_r($this->settings);
}
sleep(1);
}
print "thread1: end\n";
}
}
class MyThread2 extends Thread{
public $settings;
public function __construct($settings){
$this->settings = $settings;
}
public function run(){
print "thread2: start\n";
for($n = 0; $n < 10; $n++){
print "thread2: $n\n";
if($n == 8){
print_r($this->settings);
}
sleep(1);
}
print "thread2: end\n";
}
}
$settings = new StackableAr();
$settings['test1'] = new StackableAr();
$settings['test1']['attr1'] = 'string1';
$myThread1 = new MyThread1($settings);
$myThread2 = new MyThread2($settings);
$myThread1->start();
$myThread2->start();
for($n = 0; $n < 12; $n++){
print "main: $n\n";
sleep(1);
}
?>
即使thread1不再存在,如何使$this->settings['test2']
保持不变。我像pthread PHP example note那样说:你可以而且应该使用Stackable作为你希望传递给其他线程的所有数组的基础对象
thread1结束后$this->settings['test3']
仍然存在。但为什么不$this->settings['test2']
?
答案 0 :(得分:2)
创建对象的上下文 - 这是对象真正存在的唯一位置 - 已经消失,因此对象被销毁。
其他数据从不依赖于创建它的上下文,因为它是一个简单的类型。
当您在线程周围传递对象时,只要共享对象,就必须确保存在创建上下文,对于主进程和该进程创建的所有线程都是如此。