我是PHP的多线程初学者,使用pthreads。我尝试运行一些演示代码来理解基础知识。 所以,我已经安装了pthreads:
# php -m | grep pthreads
pthreads
# php -v
PHP 5.4.45 (cli) (built: Sep 25 2015 08:01:30)
我想运行几个连接到DB并进行查询的线程,但是使用一个共享的mysqli对象。我运行这段代码:
<?php
class SQLWorker extends Worker {
public function __construct($hostname, $username, $password, $database, $port = 3306) {
$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;
$this->database = $database;
}
public function run() {
/* the static class scope acts as a kind of thread local storage for this class */
self::$connection = new MySQLi
($this->hostname, $this->username, $this->password, $this->port);
}
public function getConnection() {
return self::$connection;
}
protected $hostname;
protected $username;
protected $password;
protected $database;
protected $port;
protected static $connection;
}
class SQLTask extends Threaded {
public function __construct($sql) {
$this->sql = $sql;
}
public function run() {
/* fetch static (thread local) connection */
$link = $this->worker->getConnection();
if ($link) {
/* execute query, keep result in local scope */
$result = $link->query($this->sql);
/* build up results as normal array */
while (($row = $result->fetch_assoc())) {
$rows[] = $row;
}
}
/* store results in a fetchable form */
$this->rows = $rows;
}
public function getResults() {
return $this->rows;
}
}
$pool = new Pool(4,
SQLWorker::connection,
["localhost", "username", "password", "database"]);
$pool->submit(
$task = new SQLTask("SELECT 1"));
$pool->shutdown();
/* you have your normal array of data here */
var_dump($task->getResults());
得到错误:
PHP Fatal error: Class 'Threaded' not found in pThreads.php on line 31
我的问题在哪里?