Skip to content

Semaphore::release() is unchecked: stray releases lift the permit count above its initial value #424

Closed

Description

@blacktrs

Semaphore::release() is unchecked: releasing more often than acquiring pushes the permit count above the constructor's value, so the semaphore stops bounding concurrency.

<?php
use function Async\{async, spawn, delay};
use Async\Semaphore;
async(function () {
    $s = new Semaphore(1);
    $s->release();
    $s->release();
    $active = 0; $max = 0; $tasks = [];
    for ($i = 0; $i < 4; $i++) {
        $tasks[] = spawn(function () use ($s, &$active, &$max) {
            $s->withPermit(function () use (&$active, &$max) {
                $active++; if ($active > $max) { $max = $active; }
                delay(0.01);
                $active--;
            });
        });
    }
    foreach ($tasks as $t) { $t->await(); }
    echo $max, "\n";
});

Prints 3 for a Semaphore(1). A stray release() is a bug in the caller; the question is what the library should do: throw (Go's semaphore.Weighted panics on over-release), clamp at the initial count, or keep the permissive behaviour and document it (it is documented as unchecked today). Related: Mutex and Semaphore wake waiters in arrival order, but a newly arriving acquirer can take the permit before an awakened waiter, so there is no strict FIFO either.

Found while writing the API reference.

Activity

  1. added
    bug
    needs-design
    area:runtime
    on Oct 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:runtimebugneeds-design

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions