[英]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.