Reputation: 502
I have the following PHP code:
<?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);
}
?>
How can I make $this->settings['test2']
persist even if thread1 doesn't exist anymore. I made it like pthread PHP example note says: You can and should use a Stackable as a base object for all arrays you wish to pass to other threads
$this->settings['test3']
persists after thread1 ended. But why not $this->settings['test2']
?
Upvotes: 1
Views: 1228
Reputation: 17158
The context that created the object - which is the only place the object really exists - is gone, and so the object is destroyed.
The other data was never dependent on the context that created it since it is of a simple type.
When you are passing objects around threads, you have to ensure the creating context exists for as long as the object is being shared, this is true for the main process and all threads created by that process.
Further reading: https://gist.github.com/krakjoe/6437782
Upvotes: 2