Skip to content

Instantly share code, notes, and snippets.

@orolyn
Created January 21, 2022 10:24
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 orolyn/7651e4127759aad1736547490baa1394 to your computer and use it in GitHub Desktop.
Save orolyn/7651e4127759aad1736547490baa1394 to your computer and use it in GitHub Desktop.
class Sample
{
private ?\Closure $callback; // objects own reference
public function start()
{
return $this->callback = $this->poll(...);
}
private function poll()
{
static $i;
$i++;
var_dump($i);
}
}
class Main
{
public function __construct(
private \WeakMap $callbacks = new \WeakMap()
)
{}
public function addCallback(\Closure $callback, ...$args)
{
$this->callbacks[$callback] = $args;
}
public function run()
{
for (;;) {
foreach ($this->callbacks as $callback => $args) {
$callback($args);
unset($callback);
usleep(100);
}
if (count($this->callbacks) < 1) {
break;
}
}
}
}
$sample = new Sample();
$main = new Main();
$main->addCallback($sample->start());
unset($sample);
$main->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment