3v4l.org

run code in 300+ PHP versions simultaneously
<?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 = array(); 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)); } ?>

preferences:
62.69 ms | 402 KiB | 5 Q