1

I am new to threads in PHP and I have a problem with classes extending Thread. I need to store an object given in the constructor parameters into a SplObjectStorage but I am unable to do it. The SplObjectStorage object remains empty even after attaching an object.

When I remove the "extends Thread", it works correctly but I need to use threads.

Here is an example :

<?php

class MyClass extends Thread
{
    protected $variable;
    public function __constructor($object)
    {
        $this->variable = new \SplObjectStorage;
        $this->variable->attach($object);

        $storage = new \SplObjectStorage;
        $storage->attach($object);

        var_dump($this->variable); // shows empty SplObjectStorage
        var_dump($storage); // shows SplObjectStorage with $object inside it
        var_dump($object); // shows the object
    }
    public function run() {}
}

Have you got an idea ? I want $this->variable to be like $storage after the attachment.

Thank you.

0

1 Answer 1

0

The author of PHP pthreads has already answered this a couple of times on Stack Overflow.

Objects not extending Threaded aren't considered thread-safe and are therefore serialized/copied by pthreads.

You can make "thread-safe" classes from normal classes at runtime with Threaded::extend(). But be very careful. The underlying implementation might not be thread-safe. (SplObjectStorage fails here, by the way.)

I'm afraid you have to create/use SplObjectStorage thread-locally.

protected static $variable; // will be NULL in thread's context

OK, I must correct myself here a bit. I'm still in the process of learning pthreads myself.

Actually, you can use normal objects as class properties. But you have to access them somewhat unconventionally (and it's not very fast):

$storage = new \SplObjectStorage;
$storage->attach($object);
$this->variable = $storage; // object gets serialized

$storage = $this->variable // object gets unserialized

// work with $storage normally...

// ...and write it back:
$this->variable = $storage

Also note that you're working on copies when using the technique above. Other threads won't see changes until you write the object back. You might want to use Threaded::synchronized() here.


You always have to keep in mind that objects and arrays will be serialized when setting a Threaded property and unserialized when getting that property.

PS: Working with strings as Threaded properties is also very slow...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.