- vprintf: documentation ( source)
- printf: documentation ( source)
<?php
/* A tasks job is to count from 0 to $limit */
class Task {
public function __construct($limit) {
$this->limit = ($limit + 1) * 100;
}
public function doWork($async) {
if ($async) {
/* do a little work and allow another task to continue */
$this->position++;
} else {
/* do all the work */
for (; $this->position < $this->limit; $this->position++);
}
}
public function hasWork() { return $this->position <= $this->limit; }
public function getPosition() { return $this->position; }
private $position = 0;
private $limit = 0;
}
/* helper for detecting completion */
function finished($tasks) {
foreach ($tasks as $task) {
if ($task->hasWork())
return false;
}
return true;
}
/* helper for printing positions */
function positions($tasks, $numeric = false) {
$positions = [];
foreach ($tasks as $task) {
$positions[] =
$numeric || $task->hasWork() ?
$task->getPosition() : "-";
}
return $positions;
}
/* create three tasks */
$tasks = array(
new Task(0),
new Task(1),
new Task(2)
);
/* execute tasks asynchronously */
while (!finished($tasks)) {
foreach ($tasks as $task) {
if ($task->hasWork()) {
$task->doWork(true);
}
vprintf( "% 4s % 4s % 4s\n", positions($tasks));
}
}
printf("------------------\n");
$tasks = array(
new Task(0),
new Task(1),
new Task(2)
);
/* execute tasks synchronously */
foreach ($tasks as $task) {
if ($task->hasWork()) {
$task->doWork(false);
}
vprintf( "% 4s % 4s % 4s\n", positions($tasks));
}
?>