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.
The first way we can send a parameter to a thread is simply providing it to our Runnable or Callable in their constructor.
If you want synchronous communication between a main thread and a processing thread, you can use a SynchronousQueue. The idea is that the main thread passes data to the processing thread by calling put() , and the processing thread calls take() .
In c++11 to pass a referenceto a thread, we have std::ref(). std::thread t3(fun3, std::ref(x)); In this statement we are passing reference of x to thread t3 because fun3() takes int reference as a parameter.
We can use join() methodto ensure all threads that started from main must end in order in which they started and also main should end in last.In other words waits for this thread to die. Calling join() method internally calls join(0);
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();
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