如何使用扩展名pthreads
将参数从我的主线程传递到PHP中的新线程?
答案 0 :(得分:4)
就像使用PHP [或任何语言]中的任何其他对象一样,您应该将参数传递给构造函数以设置成员。
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();
对于你刚刚传递的标量和简单数据,不需要采取任何特殊操作,但是如果你打算在多个线程中操作一个对象,那么对象的类应该来自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();
答案 1 :(得分:3)
从这段代码开始:
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());
?>