2014-04-10 2 views
1

Memcache가 pthread 스레드 내에서 작동하지 않는 것 같습니다. memcache에 객체가 스레드간에 공유 할 준비가 아니기 때문에 당신이, 당신은 또한 memcached와 연결을 작성하지 않도록해야합니다 memcached를에 스레드 당 연결을 만들어야합니다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

:

나는이 경고를 얻을 스레드 된 개체 컨텍스트로. 다음 코드 예

어느 좋다 :

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