安全的数据存储。我读到这个任务适合可堆叠。我继承了可堆叠,但存储中的数据未同步。
异步操作 -- 只是增加存储中的价值AsyncWatcher - 只是在存储中产生价值的回声。
问题:存储中的数据未从异步操作线程修改,存储永久包含 -1。
我正在使用线程。
class Storage extends Stackable {
public function __construct($data) {
$this->local = $data;
}
public function run()
{
}
public function getData() { return $this->local; }
}
class AsyncOperation extends Thread {
private $arg;
public function __construct(Storage $param){
$this->arg = $param->getData();
}
public function run(){
while (true) {
$this->arg++;
sleep(1);
}
}
}
class AsyncWatcher extends Thread {
public function __construct(Storage $param){
$this->storage = $param -> getData();
}
public function run(){
while (true) {
echo "In storage ". $this->storage ."'n";
sleep(1);
}
}
}
$storage = new Storage(-1);
$thread = new AsyncOperation($storage);
$thread->start();
$watcher = new AsyncWatcher($storage);
$watcher->start();
如您所见,Stackable 类有很多方法,主要用于异步操作,它们可以帮助您解决问题。您应该通过以下方式修改异步类:
class AsyncOperation extends Thread {
private $arg;
public function __construct(Storage $param){
$this->arg = $param->getData();
}
public function run(){
while (true) {
$this->arg++;
sleep(1);
}
$this->synchronized(function($thread){
$thread->notify();
}, $this);
}
}
它们的用法将是这样的:
$storage = new Storage();
$asyncOp = new AsyncOperation($storage);
$asyncOp->start();
$asyncOp->synchronized(function($thread){
$thread->wait();
}, $asyncOp);
var_dump($storage);