How do I share data between threads?
Like the method of creating a Thread, you only need to depend on the Thread class and do nothing.
This is Thread
use vennv\vapm\Thread;
class TestThread extends Thread {
public function onRun(): void {
$data = self::getSharedData();
$data["I Love PHP"] = ["PHP", "GOOD"];
self::postMainThread($data);
}
}
This is Main Thread
use vennv\vapm\Thread;
class SharedData extends Thread {
public function onRun(): void {}
}
SharedData::addShared('This is key Thread', ['data1', 'data2']); // you can use setShared() method
$class = new TestThread();
$class->start()->then(function($data) {
var_dump(SharedData::getDataMainThread());
});
Output:
array(2) {
["This is key Thread"]=>
array(2) {
[0]=>
string(5) "data1"
[1]=>
string(5) "data2"
}
["I Love PHP"]=>
array(2) {
[0]=>
string(3) "PHP"
[1]=>
string(4) "GOOD"
}
}
You should not require the php file that is registered to the thread because that will cause process errors.
Last updated