Problem with variable class variable, cross-pollution of data

So, I have a main class that calls another singleton class, but when I start multiple threads (or parallel threads) I get a cross infection of the data. This is a very simple version to explain the problem. All setter / getters variables are in Singleton and are called and set by the main class.

class A {

    public function doSomething($var) {
        Singleton::instance()->setVar($var);
    }

    public function showSomething() {
        return Singleton::instance()->getVar();
    }

}

// Singleton

class Singleton {
    private static $instance = null;
    private $var;

    public static function instance() {
        if(!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }
        return self::$instance;
    }

    public function setVar($var) {
        $this->var = $var;
    }

    public function getVar() {
        return $this->var;
    }
}

test script 1:

$actions = Array(
    'one',
    'two',
    'three',
);

foreach($actions as $act) {
    $action = new A();
    $action->doSomething($act);
    echo "Action: ".$action->showSomething()."\n";
    sleep(2);
}

test script 1 output will have:

one
two
three

test script 2:

$actions = Array(
    '1',
    '2',
    '3',
);

foreach($actions as $act) {
    $action = new A();
    $action->doSomething($act);
    echo "Action: ".$action->showSomething()."\n";
    sleep(2);
}

test script 2 will have:

1
2
3
one
two
three

(not in this order and one of the values ​​may be missing)

So, why is test 1 included in the results of test 2 while running both scenarios at the same time?

How do I test:

open two terminals, run one script in each terminal (hence sleep) so that I can see data pollution.

+3
2

, test1 test2 - . , , , ( ) , (, , ).

- , test2 test1.

, , , , . . . , . , .

, IDE , , .

class Singleton {
    private static $instance = null;
    private $var;

    public static function instance() {
        if(!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }
        echo 'Singleton Instantiated.',"\n";
        return self::$instance;
    }

    public function setVar($var) {
        echo 'Singleton::setVar(', $var, ').',"\n";
        $this->var = $var;
    }

    public function getVar() {
        echo 'Singleton::getVar(): "', $var, '".',"\n";
        return $this->var;
    }
}
+3

, , .

1 2, 1 2, , .

10 , .

OP , .

, . , .

+2

All Articles