Skip to content

Instantly share code, notes, and snippets.

@krakjoe
Created January 10, 2015 09:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krakjoe/6a9419704aaacfbc6f69 to your computer and use it in GitHub Desktop.
Save krakjoe/6a9419704aaacfbc6f69 to your computer and use it in GitHub Desktop.
Asynchronous Concurrency - Vanilla PHP
<?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