How can I pass a parameter from my main thread to a new thread in PHP using the extension pthreads
?
Something similar to this How can I pass a parameter to a Java Thread? just in PHP.
How can I pass a parameter from my main thread to a new thread in PHP using the extension pthreads
?
Something similar to this How can I pass a parameter to a Java Thread? just in PHP.
Starting from this code:
http://www.php.net/manual/en/thread.start.php
<?php
class My extends Thread {
public $data = "";
public function run() {
/** ... **/
}
}
$my = new My();
$my->data = "something"; // Pass something to the Thread before you actually start it.
var_dump($my->start());
?>
Just as you do with any other object in PHP [or any lanugage], you should pass parameters to constructors to set members.
class My extends Thread {
public function __construct($greet) {
$this->greet = $greet;
}
public function run() {
printf(
"Hello %s\n", $this->greet);
}
}
$my = new My("World");
$my->start();
$my->join();
No special action need be taken for scalars and simple data that you are just passing around, however should you intend to manipulate an object in multiple threads, the object's class should descend from pthreads:
class Greeting extends Threaded {
public function __construct($greet) {
$this->greet = $greet;
}
public function fetch() {
return $this->greet;
}
protected $greet;
}
class My extends Thread {
public function __construct(Greeting $greet) {
$this->greet = $greet;
}
public function run() {
printf(
"Hello %s\n", $this->greet->fetch());
}
}
$greeting = new Greeting("World");
$my = new My($greeting);
$my->start();
$my->join();