1. Go to this page and download the library: Download appserver-io/concurrency library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
class Storage
{
public $data = array();
/**
* @Synchronized
*/
public function all() {
return $this->data;
}
/**
* @Synchronized
*/
public function set($key, $value) {
$this->data[$key] = $value;
}
/**
* @Synchronized
*/
public function get($key) {
if ($this->has($key)) {
return $this->data[$key];
}
}
/**
* @Synchronized
*/
public function has($key) {
return isset($this->data[$key]);
}
/**
* @Synchronized
*/
public function del($key) {
unset($this->data[$key]);
}
/**
* @Synchronized
*/
public function inc($key) {
if ($this->has($key)) {
++$this->data[$key];
}
}
/**
* @Asynchronous
*/
public function dump() {
echo var_export($this->all(), true) . PHP_EOL;
}
}
class Task extends Thread {
public static function simulate($maxThreads) {
$t = array();
for ($i=0; $i<$maxThreads; $i++) {
$t[$i] = new self();
$t[$i]->start(PTHREADS_INHERIT_ALL | PTHREADS_ALLOW_GLOBALS);
}
for ($i=0; $i<$maxThreads; $i++) {
$t[$i]->join();
}
}
public function run() {
// get the storage object
$storage = \AppserverIo\Concurrency\ExecutorService::__getEntity('data');
// add thread signature
$storage->set($this->getThreadId(), __METHOD__);
// increase internal counter
$storage->inc('counter');
}
}
define('AUTOLOADER', 'vendor/autoload.php');
');
use \AppserverIo\Concurrency\ExecutorService as ExS;
// init executor service
ExS\Core::init(AUTOLOADER);
// create storage instance with alias data
$data = ExS\Core::newFromEntity('Storage', 'data');
// preinit counter
$data->set('counter', 0);
// simulate multithreaded tasks
Task::simulate(10);
// dump data async
$data->dump();
echo 'finished' . PHP_EOL;
// shutdown executor service and its entities
ExS\Core::shutdown();