pmmp / ext-pmmpthread

Fork of https://github.com/krakjoe/pthreads with a revamped API and PHP 8.1+ support
Other
82 stars 15 forks source link

Inconsistent behaviour for string properties of threads #119

Closed platz1de closed 1 year ago

platz1de commented 1 year ago

Environment

Reproducing Code

Example 1:

<?php

use pmmp\thread\Thread;

$thread = new class extends Thread {
    public int $integer = 0;
    public bool $boolean = false;
    public string $string = "Initial";
    public function run() : void {
        $this->integer = 1;
        $this->boolean = true;
        $this->string = "Hello World";
    }
};

$thread->string; //Commenting this out will make the issue go away
$thread->start(Thread::INHERIT_NONE) && $thread->join();
var_dump($thread->integer, $thread->boolean, $thread->string);
?>

The placement of the marked line doesn't matter as long as the property is accessed from the main thread first (e.g. by setting or just referencing like in this example).

Example 2:

<?php

use pmmp\thread\Thread;

$thread = new class extends Thread {
    public string $string = "Initial";
    public function run() : void
    {
        usleep(500000);
        for ($i = 0; $i < 3; $i++) {
            $this->string = "Thread: " . $i;
            sleep(1);
        }
    }
};

$thread->start(Thread::INHERIT_NONE);
$thread->string; //Commenting this out will make the issue go away
sleep(1);
while ($thread->isRunning()) {
    echo $thread->string . PHP_EOL;
    sleep(1);
}
?>

Expected Output

int(1)
bool(true)
string(11) "Hello World"
Thread: 0
Thread: 1
Thread: 2

Actual Output

int(1)
bool(true)
string(7) "Initial"
Initial
Thread: 1
Thread: 2

Commenting the marked line produces the expected output.

dktapps commented 1 year ago

This is most likely a cache issue from single-copy strings.

dktapps commented 1 year ago

It seems like this is an OPcache-specific issue. If OPcache is disabled, the bug doesn't occur.