-
-
Save krakjoe/6a9419704aaacfbc6f69 to your computer and use it in GitHub Desktop.
Asynchronous Concurrency - Vanilla PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Task { | |
function Task($id, $start, $end) { | |
$this->id = $id; | |
$this->start = $start; | |
$this->end = $end; | |
$this->pos = $this->start; | |
} | |
function execute() { | |
if ($this->pos < $this->end) { | |
return $this->pos++; | |
} else return false; | |
} | |
} | |
$range = range(1, 100); | |
$ranges = array_chunk($range, 10); | |
$tasks = array(); | |
while (count($ranges)) { | |
$range = array_shift($ranges); | |
$tasks[] = new Task( | |
count($tasks) + 1, | |
array_shift($range), | |
array_pop($range)); | |
} | |
while (count($tasks)) { | |
foreach ($tasks as $id => $task) { | |
if ($task->execute() === false) { | |
printf("task %d complete\n", $task->id); | |
unset($tasks[$id]); | |
} else printf("task %d position %d\n", $task->id, $task->pos); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment