Memcache似乎没有在pthread线程内工作。
我收到了这个警告:
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();
}
答案 0 :(得分:2)
由于memcache对象不准备在线程之间共享,因此必须为每个线程创建一个到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();
}