我在phreads中使用了池和Promise(等待线程的结果)的组合,但我不太擅长编程。我试图在我编写的代码中访问变量$ variable" //我不知道如何在函数checkvariable"中访问变量$ variable。
但是我不知道这是否是解决问题的正确方法,我想要运行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);
&GT;
我尝试了这个,但它确实做了工作:
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);
});
答案 0 :(得分:0)
使用$variable = $this->variable;
$promise = new Promise(function () use ($variable) {
return checkvariable($variable)
});
关键字
isspace()