2013-12-17 35 views
0

我試圖做一個pthreads類,它不斷更新我將在腳本的其他地方使用的變量。 pthreads類應該提取URL的內容,將值賦給變量,然後重複。用pthreads連續更新數組

$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); 
} 

$對需要不斷更新,並顯示在屏幕上

+1

1.爲什麼你需要一個線程呢? 2.不使用互斥量從線程訪問全局變量是災難的祕訣。 3.「while(true)」對於輸入和執行都更快,並且還具有不超級跛腳的優點。 :I – Sammitch

+0

我將有幾個這樣的線程同時運行和更新。 – Jonathan

回答

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; 
    } 
} 
?> 

它似乎並不像一個很好的利用資源,讓每個線程的請求,你可能真的不希望在現實世界中做到這一點。睡眠不適合用於多線程,它不會使線程處於接受狀態。

全局變量在線程的上下文中沒有效果,它們像範圍一樣工作,但它並不包含線程的範圍。