Question

Memcache doesn't seem to work inside a pthread thread.

I get this warning:

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

Solution

Since the memcache objects are not prepared to be shared among threads, you must create a connection per thread to memcached, you must also be sure not to write the memcached connection to the threaded object context.

Either of the following code examples are good:

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

The static scope of classes represent a kind of thread local storage, making the following code also good:

<?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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top