[英]Using Threaded Object as Multidimensional Associative Array PHP Pthreads
[英]Associative array as object property in PHP (using pthreads)
我的对象中有一个关联数组类型属性。 这是示例:
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
值不变。 为了增加此类属性的价值,我应该使用哪种适当的构造。 它可以很好地工作而不将其传递给线程对象,但是我需要它完成我的任务。 谢谢。
由于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
是同步的,所以一次最多只能有一个线程执行一次查询,因此可以确保没有两个线程可以执行两次相同的查询。 您也许可以提出一种更高效的方式(按记录)同步对缓存的访问,但这是一个很好的起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.