我的对象中有一个关联数组类型属性。这是一个例子:
class GetInfo {
private $domains_ip = array();
function get_ip($domain)
{
print_r($this->domains_ip);
$ip = gethostbyname($domain);
$this->domains_ip[$ip] = $domain;
return $ip;
}
}
class my_thread extends Thread {
private $get_info_object;
function __construct(GetInfo $obj)
{
$this->get_info_object = $obj;
}
function check_ip($domain)
{
echo $this->get_info_object->get_ip($domain);
}
}
$o = new GetInfo();
$t = new my_thread($o);
$t->check_ip("google.com");
$t->check_ip("pivo.com");
但问题是$this->domains_ip
值不会发生变化。我应该使用什么样的结构来增加这种类型的财产的价值。它工作正常而不将其传递给线程对象,但我需要完成我的任务。谢谢。
答案 0 :(得分:1)
由于GetInfo
不是来自pthreads
(它不是Threaded
):
$this->get_info_object = $obj;
这会导致$obj
的序列表示存储为Thread
的成员。这导致GetInfo
的成员被序列化并将产生意外结果。
解决方案是用适当的对象替换你对数组的使用,以下代码适用于PHP 7(pthreads v3 +):
<?php
class GetHostByNameCache extends Threaded {
public function lookup(string $host) : string {
return $this->synchronized(function() use($host) {
if (isset($this->cache[$host])) {
return $this->cache[$host];
}
return $this->cache[$host] = gethostbyname($host);
});
}
private $cache = [];
}
class Test extends Thread {
public function __construct(GetHostByNameCache $cache, string $host) {
$this->cache = $cache;
$this->host = $host;
}
public function run() {
var_dump(
$this->cache->lookup($this->host));
}
private $cache;
}
$tests = [];
$cache = new GetHostByNameCache();
$domains = [
"google.co.uk",
"google.com",
"google.co.jp",
"google.co.in",
"google.co.ca",
"google.net"
];
for ($test = 0; $test < count($domains); $test++) {
$tests[$test] = new Test($cache, $domains[$test]);
$tests[$test]->start();
}
foreach ($tests as $test)
$test->join();
var_dump($cache);
?>
这会产生类似的结果:
string(14) "216.58.198.195"
string(14) "216.58.198.206"
string(14) "216.58.198.195"
string(14) "216.58.198.195"
string(12) "66.196.36.16"
string(14) "216.58.198.196"
object(GetHostByNameCache)#1 (1) {
["cache"]=>
object(Volatile)#2 (6) {
["google.co.uk"]=>
string(14) "216.58.198.195"
["google.com"]=>
string(14) "216.58.198.206"
["google.co.jp"]=>
string(14) "216.58.198.195"
["google.co.in"]=>
string(14) "216.58.198.195"
["google.co.ca"]=>
string(12) "66.196.36.16"
["google.net"]=>
string(14) "216.58.198.196"
}
}
需要注意的重要事项是:
Threaded
。Volatile
。lookup
例程逻辑已同步。由于lookup
已同步,因此一次只能执行一次查找,这可确保没有两个线程可以执行两次相同的查找。您可能能够提出一种更有效的同步访问缓存的方法(基于每个记录),但这是一个很好的起点。