1

I need little help with pthreads in php. I have following class

namespace le\Thread;

class Thread extends \Thread
{

    protected $method;
    protected $params;
    protected $result = null;
    protected $joined = false;

    /**
     * Provide a passthrough to call_user_func_array
     **/
    public function __construct($method, $params)
    {
        $this->method = $method;
        $this->params = $params;
    }

    /**
     * The smallest thread in the world
     **/
    public function run()
    {
        if (($this->result = call_user_func_array($this->method, $this->params))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Static method to create your threads from functions ...
     **/
    public static function process($method, $params)
    {
        $thread = new self($method, $params);
        if ($thread->start()) {
            return $thread;
        }
        /** else throw Nastyness **/
    }

    /**
     * Do whatever, result stored in $this->result, don't try to join twice
     **/
    public function getResult()
    {
        if (!$this->joined) {
            $this->joined = true;
            $this->join();
        }

        return $this->result;
    }
}

and I want to use it this way. In another class I have CPU heavy method which I want to process multithreaded.

$thread = Thread::process([$this, 'method'], $dataArray);
$thread->getResult();

but It throws following error

Serialization of 'Closure' is not allowed

How can I fix that? Is that even possible?

Jakub Riedl
  • 1,066
  • 2
  • 10
  • 27
  • The inability to serialize a closure is a limitation imposed by Zend; they are not suitable for storage as members of a ```Threaded``` object. – Joe Watkins Apr 28 '14 at 11:20
  • OK I understand, is there some workaround? Or another way how to reach the target? – Jakub Riedl Apr 28 '14 at 11:27
  • It seems the code in your question is from the example distributed with pthreads that contains the answer to that: https://github.com/krakjoe/pthreads/blob/master/examples/CallAnyFunction.php – Joe Watkins Apr 30 '14 at 09:25
  • I was inspired by this example. It is working for basic functions but not when sending object as attribute. But I need to process much more advanced functions. – Jakub Riedl Apr 30 '14 at 10:58
  • Then object orientate the code ;) – Joe Watkins Apr 30 '14 at 11:08

0 Answers0