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();
}
由于内存缓存对象不准备在线程之间共享,因此必须为每个线程创建到内存缓存的连接,还必须确保不要将内存缓存连接写入线程对象上下文。
以下任何一个代码示例都不错:
<?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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句