关联数组作为对象 属性 in 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是同步的,一次只能有一个线程执行查找,这确保没有两个线程可以执行相同的查找两次。您也许可以想出一种更有效的方法来同步对缓存的访问(基于每条记录),但这是一个很好的起点。