Skip to content

Instantly share code, notes, and snippets.

@unglud
Created November 30, 2017 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unglud/cb66e02949ba2337e63c8d6a051db5d5 to your computer and use it in GitHub Desktop.
Save unglud/cb66e02949ba2337e63c8d6a051db5d5 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
use Symfony\Component\Filesystem\LockHandler;
/**
* Class Forklift
*
* @package C24Shopping\Core\App\Service
*/
class Forklift
{
private $processNumber = 3;
private $worker;
public function __construct()
{
$this->file = get_config('paths/filestore') . 'data.json';
$this->put([]);
}
protected function put($data)
{
file_put_contents($this->file, serialize($data));
}
public function run($data)
{
for ($i = 0; $i < $this->processNumber; $i++) {
$process = array_shift($data);
$pid = pcntl_fork();
if (!$pid) {
$this->fork($process);
exit(0);
}
}
// we are the parent (main), check child's (optional)
while (pcntl_waitpid(0, $status) != -1) {
pcntl_wexitstatus($status);
}
if (count($data)) {
$this->run($data);
}
}
/**
* Will be run only by children.
* Does the actual work.
* MUST be overwritten
*
*/
protected function fork($data)
{
if (empty($data)) {
return 1;
}
$result = call_user_func($this->worker, $data);
$lock = new LockHandler('accurals.lock');
if ($lock->lock(true)) {
$ar = $this->get();
$ar[] = $result;
$this->put($ar);
$lock->release();
}
return 1;
}
/**
* @return mixed
*/
protected function get()
{
return unserialize(file_get_contents($this->file));
}
public function getResult()
{
return $this->get();
}
public function addWorker($worker)
{
$this->worker = $worker;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment