Skip to content

Commit

Permalink
Add AwaitGroup support for GoroutineGen!
Browse files Browse the repository at this point in the history
  • Loading branch information
VennDev authored Aug 26, 2024
1 parent 1cb38e2 commit cdc95fd
Showing 1 changed file with 112 additions and 0 deletions.
112 changes: 112 additions & 0 deletions src/vennv/vapm/AwaitGroup.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

/**
* Vapm - A library support for PHP about Async, Promise, Coroutine, Thread, GreenThread
* and other non-blocking methods. The library also includes some Javascript packages
* such as Express. The method is based on Fibers & Generator & Processes, requires
* you to have php version from >= 8.1
*
* Copyright (C) 2023 VennDev
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/

declare(strict_types=1);

namespace vennv\vapm;

use Generator;

interface AwaitGroupInterface
{

/**
* @param int $count
* @return void
*
* This function is used to add the count to the group
*/
public function add(int $count): void;

/**
* @return Generator
*
* This function is used to decrement the count
*/
public function done(): Generator;

/**
* @return bool
*
* This function is used to check if the count is zero
*/
public function isDone(): bool;

/**
* @return int
*
* This function is used to get the count
*/
public function getCount(): int;

/**
* @return void
*
* This function is used to wait for the count to be zero
*/
public function reset(): void;

}

final class AwaitGroup implements AwaitGroupInterface
{

private int $count = 0;

public function add(int $count): void
{
$this->count += $count;
}

public function done(): Generator
{
$this->count--;
yield;
}

public function isDone(): bool
{
return $this->count === 0;
}

public function getCount(): int
{
return $this->count;
}

public function reset(): void
{
$this->count = 0;
}

public function wait(): void
{
while ($this->count > 0) {
// Wait for the count to be zero
}
}

public function __destruct()
{
$this->reset();
}

}

0 comments on commit cdc95fd

Please sign in to comment.