用pthreads连续更新数组

时间:2013-12-17 23:37:20

标签: php arrays api pthreads

我试图创建一个pthreads类,它不断更新我将在脚本中的其他地方使用的变量。 pthreads类应该提取URL的内容,将值赋给变量,sleep和repeat。

$pair = array();

class Pair extends Thread {
    public function __construct($url){
         $this->url = $url;
    }

    public function run() {
        global $pair;
        while (true){
        $pair = json_decode("https://btc-e.com/api/2/".$this->url."/ticker", true);
        sleep(5);
        }
    }
}

$BTC_USD = new Pair("btc_usd");

while (true){
    print_r($pair);
    sleep(5);
}

$ pair需要不断更新并打印到屏幕上

1 个答案:

答案 0 :(得分:1)

<?php
define ('SECOND', 1000000);

class Repeater extends Thread {
    public $url;
    public $data;

    public function __construct($url) {
        $this->url = $url;
    }

    public function run() {
        do {
            /* synchronize the object */
            $this->synchronized(function(){
                /* fetch data into object scope */
                $this->data = file_get_contents($this->url);

                /* wait or quit */
                if (!$this->stop)
                    $this->wait();
            });
        } while (!$this->stop);
    }

    public function stop() {
        /* synchronize the object */
        $this->synchronized(function(){
            /* set stop */
            $this->stop = true;

            /* notify the object (could/should be waiting) */
            $this->notify();
        });
    }

    public function getData() {
        /* fetch data / wait for it to arrive */
        return $this->synchronized(function(){
            return $this->data;
        });
    }
}

/* to provide a limit for the example */
$iterations = 5;

/* the url etc is not important */
$repeat = new Repeater("http://www.google.com");
$repeat->start();

/* this will only return when there is data */
while (($data = $repeat->getData())) {
    var_dump(strlen($data));

    $repeat->synchronized(function($repeat){
        /* notify allows the thread to make he next request */
        $repeat->notify();
        /* waiting here for three seconds */
        $repeat->wait(3 * SECOND);
    }, $repeat);

    if (!--$iterations) {
        /* because examples should be sensible */
        $repeat->stop();
        break;
    }   
}
?>

对于每个线程请求一个好的资源似乎并不是很好,你可能并不真的想在现实世界中这样做。睡眠不适合用于多线程,它不会使线程处于接受状态。

globals在线程上下文中没有任何作用,它们通常与范围有关,但它不包括线程的范围。