gpt4 book ai didi

php - 如何使用PHP pthread删除对可堆叠对象的所有引用?

转载 作者:行者123 更新时间:2023-12-03 13:04:37 25 4
gpt4 key购买 nike

我正在PHP中尝试使用pthreads。引用Joe的gist覆盖池,我创建了一个工作线程池,并提交了可堆叠对象的实例。线程和工作都按我的预期进行,但是似乎主线程/上下文没有(完全)取消对Stackable对象的引用,因此内存使用无限增加,因为它保留了越来越多的实例。

它似乎确实清除/取消了可堆叠对象的所有属性,因此内存使用并不能很快通过屋顶,但是它确实会永远增加,因此不能有效地用于长时间运行的过程。我希望我只是做错了什么。这是示例代码,将演示我的意思:

class W extends Worker {
public function run(){}
}
class S extends Stackable {
public $id;
public function run() {
$this->id = uniqid();
}
public function __destruct () {
// $this->id will be null here when the main thread destroys its copy of this
if ($this->id === null) {
echo "nullified stackable destroyed\n";
} else {
echo "stackable {$this->id} destroyed\n";
}
}
}

$pool = new Pool(3, W::class);
$i = 0;
while ($i++ < 10) {
$pool->submit(new S());
}
sleep(1); // to let threads finish

$pool->collect(function (S $s) {
echo "collected stackable {$s->id}\n";
return true;
});
$pool->shutdown();
echo "script exit - here come the destructions of all the accumulated stackables\n";

最佳答案

作为PHP7升级的一部分,pthreads v3进行了许多改进。

您会发现此代码的PHP7版本按预期工作:

<?php
class W extends Worker {
public function run(){}
}
class S extends Threaded implements Collectable {
public $id;

public function run() {
$this->id = uniqid();
$this->garbage = true;
}

public function __destruct () {
if ($this->id === null) {
echo "nullified stackable destroyed\n";
} else {
echo "stackable {$this->id} destroyed\n";
}
}

public function isGarbage() : bool { return $this->garbage; }

private $garbage = false;
}

$pool = new Pool(3, W::class);
$i = 0;
while ($i++ < 10) {
$pool->submit(new S());
}

while ($pool->collect(function (S $s) {
if ($s->isGarbage()) {
echo "collected stackable {$s->id}\n";
}
return $s->isGarbage();
})) continue;

$pool->shutdown();
echo "script exit - here come the destructions of all the accumulated stackables\n";

建议新项目使用PHP7和pthreads v3,它远远优于PHP5和pthreads v2。

关于php - 如何使用PHP pthread删除对可堆叠对象的所有引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30870809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com