存储中的数据不是从线程修改的

时间:2014-11-24 16:02:07

标签: php multithreading pthreads

安全存储数据。我读到这个任务适合Stackable。 我继承了Stackable,但存储中的数据不同步 AsyncOperation - 只是增加存储中的值 AsyncWatcher - 只是回忆存储中的价值。

问题:存储中的数据未从AsyncOperation线程修改,存储永久包含-1。

我正在使用pthreads。

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();

1 个答案:

答案 0 :(得分:1)

如您所见,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);