1

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

1 回答 1

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();
}
于 2014-04-10T06:31:09.620 回答