I am trying to code php threads. I'm creating a DOMDocument in the constructor but for some reason the newly created document, although assigned to a member variable, disappears.
Code-listing 1:
class workerThread extends Thread {
private $document;
private $i;
public function __construct($i){
$this->document = new DOMDocument();
$this->i = $i;
}
public function run(){
try{
$root = $this->document->createElement("Root");//can't fetch this
$this->document->appendChild($root);
}catch(RuntimeException $e){
return false;
}
}
public function getRoot(){
return $this->document->documentElement;
}
}
for($i=0;$i<10;$i++){
$workers[$i] = new workerThread($i);
$workers[$i]->start();
}
for($i=0;$i<10;$i++){
$workers[$i]->join();
}
?>
I tried instanciating the new DOMDocument outside the constructor and use them as an argument in the constructor like in code-listing 2 but it doesn't change a thing.
Code-listing 2:
for($i=0;$i<10;$i++){
$documents[$i] = new DOMDocument();
$workers[$i] = new workerThread($documents[$i], $i);
$workers[$i]->start();
}
The constructor looks like this:
Code-listing 3:
public function __construct($doc, $i){
$this->document = $doc;
$this->i = $i;
}
I want to be able to create the DOMDocument outside or inside the thread (whether it's in the constructor, the run function or another function), use it in the run function and retrieve it's root from outside the thread that processed it.
class workerThread extends Thread {
private $document;
private $i;
public function __construct($i){
$this->document = new DOMDocument();
$this->i = $i;
}
public function run(){
try{
$root = $this->document->createElement("Root");//can't fetch this
$this->document->appendChild($root);
$this->xml = $this->document->saveXML(); // <---
}catch(RuntimeException $e){
return false;
}
}
public function getRoot(){
return $this->document->documentElement;
}
}
for($i=0;$i<10;$i++){
$workers[$i] = new workerThread($i);
$workers[$i]->start();
}
for($i=0;$i<10;$i++){
$workers[$i]->join();
$workers[$i]->xml; // <---
}
Let’s start off easy with a simple web crawling example.
<?php
class SearchGoogle extends Thread
{
public function __construct($query)
{
$this->query = $query;
}
public function run()
{
$this->html = file_get_contents('http://google.fr?q='.$this->query);
}
}
Once join is called, we can be sure the class is holding our results:
$job = new SearchGoogle('cats');
$job->start();
// Wait for the job to be finished and print results
$job->join();
echo $job->html;
Please read full documents https://blog.madewithlove.be/post/thread-carefully/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With