0

here is a simple example of what I am not understanding :

<?php

class classA {

    private $z = 1;

    public function __construct() {
        $this->b = new classB;
        $this->b->setRefonClassA($this);
        $this->b->start();
    }

    function changeZ() {
        echo "ChangeZ : z=" . $this->z . "\n";
        $this->z = 666;
        echo "ChangeZ : z=" . $this->z . "\n";
    }

    function showZ() {
        echo "showZ : z=" . $this->z . "\n";
    }

}

class classB extends Thread {

    function setRefOnClassA($classA) {
        $this->classA = $classA;
    }

    function run() {
        $this->classA->changeZ();
        $this->classA->showZ();
    }

}

$test = new classA(); ?>

The result are :

ChangeZ : z=1  
ChangeZ : z=666  
showZ : z=1  

I was expecting that showZ=666. Why z=1 ?
I'm clearly missing something here.
Thanks in advance

2 Answers 2

1

Can you try extending classA from Stackable?

There is a similar problem:

pthread Thread objects reset their state

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

3 Comments

If classA extends Stackable it seems that it's not allowed to start the b thread. (Error : Warning: pthreads has detected an attempt to start classB from an invalid context, the creating context must start classB in ...)
Strange. The linked problem seems to be really similar.
My bad, it works if I do exactly as showed in the example you linked.
1

Read this: https://gist.github.com/krakjoe/6437782

You have two problems, first classA is not thread safe, if you don't descend from pthreads it is serialized when set as a member of classB. If classA does descend from pthreads, when you write it to classB you loose the real reference and pthreads will not allow you to access the same functionality - it thinks you are in another thread.

The key is, "You are responsible for the objects you create", this means, if you intend to share an object among threads, you must retain a direct reference to it in the scope that created the object.

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.