私はプールでプロミス(スレッドからの結果を待ちます)の組み合わせを使用していますが、プログラミングはあまりよくありません。私は変数$変数を私が書いたコードでアクセスできるようにしようとしています。//関数checkvariableに対して変数$変数にアクセスする方法がわかりません。PHPがプールを持ち、結果を収集するのを待っています
しかしこれは私の問題を解決する正しい方法、私は10スレッドを実行したいと思うし、結果を返すために実行する別の10スレッドが必要な各スレッドで。結果が出ると、最初の10個のスレッドのうちの1個がタスクを実行して停止します。
私はあなたの助けに非常に感謝しています! ?
<?php
class Pool extends Pool {
public $data = [];
public function process() {
// Run this loop as long as we have
// jobs in the pool
while (count($this->work)) {
$this->collect(function (CheckThis $job) {
// If a job was marked as done
// collect its results
if ($job->isGarbage()) {
$this->data[$job->query] = $job->html;
}
return $job->isGarbage();
});
}
// All jobs are done
// we can shutdown the pool
$this->shutdown();
return $this->data;
}
}
class CheckThis extends Collectable {
public function __construct($variable) {
$this->variable = $variable;
}
public function run() {
// $this->variable exists here
$promise = new Promise(function() {
// I don't know how to access the variable $variable here for the function checkvariable
return checkvariable($variable);
});
$promise->then(function ($results) {
if ($results) {
workonresult();
}
});
$this->setGarbage();
}
}
class Promise extends Thread {
public function __construct(Closure $closure) {
$this->closure = $closure;
$this->start();
}
public function run() {
$this->synchronized(function() {
$closure = $this->closure;
$this->result = $closure();
$this->notify();
});
}
public function then(callable $callback) {
return $this->synchronized(function() use ($callback) {
if (!$this->result) {
$this->wait();
}
$callback($this->result);
});
}
}
$pool = new Pool(2, Worker::class);
$pool->submit(new CheckThis($variable1));
$pool->submit(new CheckThis($variable2));
$data = $pool->process();
var_dump($data);
>
私はこれを試してみましたが、それはofcourseの仕事をdoes'nt:
public function run() {
$variable = $this->variable;
$promise = new Promise(function ($variable) {
return checkvariable($variable);
});
更新、これはどちらか動作しません:
public function run() {
$variable = $this->variable;
$promise = new Promise(function() use ($variable) {
return checkvariable($variable);
});
あなたは 'use'キーワードをお探しですか? – Chay22
どういう意味ですか? – Daniel
私の答えは以下の通りです – Chay22