2014-04-10 26 views
1

Memcache似乎在pthread線程中不起作用。PHP:Pthread + Memcache的麻煩

我得到這樣的警告:

Warning: Memcache::get(): No servers added to memcache connection in test.php on line 15 



    class Test extends Thread { 

    protected $memcache; 

    function __construct() { 
     $this->memcache = New Memcache; 
     $this->memcache->connect('localhost',11211) or die("Could not connect"); 
    } 

    public function run() { 
     $this->memcache->set('test', '125', MEMCACHE_COMPRESSED, 50); 
     $val = $this->memcache->get('test');p 
     echo "Value $val."; 
     sleep(2); 
    } 

} 

$threads = []; 
for ($t = 0; $t < 5; $t++) { 
    $threads[$t] = new Test(); 
    $threads[$t]->start(); 
} 

for ($t = 0; $t < 5; $t++) { 
    $threads[$t]->join(); 
} 

回答

2

由於內存緩存對象不準備線程之間共享,必須創建memcached的每個線程的連接,你還必須確保不寫memcached的連接到線程對象上下文。

的下面的代碼示例無論是好的:

<?php 
class Test extends Thread { 

    public function run() { 
     $memcache = new Memcache; 

     if (!$memcache->connect('127.0.0.1',11211)) 
      throw new Exception("Could not connect"); 

     $memcache->set('test', '125', MEMCACHE_COMPRESSED, 50); 
     $val = $memcache->get('test'); 
     echo "Value $val.\n"; 
    } 

} 

$threads = []; 
for ($t = 0; $t < 5; $t++) { 
    $threads[$t] = new Test(); 
    $threads[$t]->start(); 
} 

for ($t = 0; $t < 5; $t++) { 
    $threads[$t]->join(); 
} 

類的靜態範圍代表了一種線程本地存儲,使得下面的代碼也不錯:

<?php 
class Test extends Thread { 
    protected static $memcache; 

    public function run() { 
     self::$memcache = new Memcache; 

     if (!self::$memcache->connect('127.0.0.1',11211)) 
      throw new Exception("Could not connect"); 

     self::$memcache->set('test', '125', MEMCACHE_COMPRESSED, 50); 
     $val = self::$memcache->get('test'); 
     echo "Value $val.\n"; 
    } 

} 

$threads = []; 
for ($t = 0; $t < 5; $t++) { 
    $threads[$t] = new Test(); 
    $threads[$t]->start(); 
} 

for ($t = 0; $t < 5; $t++) { 
    $threads[$t]->join(); 
}