Skip to content

Latest commit

 

History

History
1002 lines (700 loc) · 36.4 KB

coroutines.md

File metadata and controls

1002 lines (700 loc) · 36.4 KB

Coroutines

Introduction

Hypervel uses Swoole coroutines to run many tasks within a single worker process. When one coroutine waits for input or output (I/O), such as a network request, Redis command, database query, file operation, or timer, the worker may continue running other coroutines. This allows I/O-heavy applications to handle many tasks at once without creating a separate operating system process or thread for each request.

A coroutine runs a function that can pause and later resume from the same point. Swoole switches between coroutines when one reaches an operation that can pause, such as an I/O operation supported by Swoole, a channel operation, a sleep, or an explicit coroutine call. Ordinary PHP code continues running until it reaches one of these operations.

Hypervel uses this model for HTTP requests, console commands, queued jobs, scheduled tasks, tests, and I/O connection pools. Store request-specific and coroutine-specific state in coroutine context instead of global variables or mutable static properties.

For a detailed overview of Hypervel's runtime model, see the introduction.

Coroutines and Concurrent Tasks

If your application needs to run several independent tasks and collect their results, you should start with Hypervel's concurrency APIs. The Concurrency facade provides a high-level API that works with the rest of the framework.

Use the lower-level coroutine APIs in this guide when you need to start work without waiting for a result, limit how many coroutines may run, clean up when a coroutine exits, use channels or locks, customize waiting, or control how context is copied.

Creating Coroutines

Hypervel provides the Hypervel\Coroutine\Coroutine class and several helper functions in the Hypervel\Coroutine namespace.

Running Code in a Coroutine Container

Most Hypervel entry points already run inside a coroutine. This includes HTTP requests, Hypervel console commands, queue workers, and framework tests.

If your code starts outside a coroutine and needs coroutine support, you may use the run function to create a coroutine container:

use Hypervel\Coroutine\Coroutine;

use function Hypervel\Coroutine\run;

echo Coroutine::id(); // -1

run(function () {
    echo Coroutine::id(); // A positive coroutine ID...
});

You may pass Swoole hook flags as the second argument:

use function Hypervel\Coroutine\run;

run(function () {
    // ...
}, SWOOLE_HOOK_ALL);

Warning

The run function may only be called outside an existing coroutine. Calling it inside a coroutine will throw an exception.

Getting the Current Coroutine ID

You may retrieve the current coroutine ID using the id method:

use Hypervel\Coroutine\Coroutine;

$coroutineId = Coroutine::id();

When code is running outside a coroutine, Coroutine::id() returns -1. Inside a coroutine, it returns a positive integer.

Parent Coroutine IDs

You may retrieve the parent coroutine ID using the parentId method:

use Hypervel\Coroutine\Coroutine;

$parentId = Coroutine::parentId();

When the current coroutine is a top-level coroutine, the parent ID is 0. You may also pass a coroutine ID to inspect the parent of another coroutine:

$parentId = Coroutine::parentId($coroutineId);

Determining if Code is Running in a Coroutine

The inCoroutine method determines if the current code is running inside a coroutine:

use Hypervel\Coroutine\Coroutine;

if (Coroutine::inCoroutine()) {
    // ...
}

Creating a Child Coroutine

You may create a child coroutine using the go function:

use function Hypervel\Coroutine\go;

go(function () {
    sleep(1);

    echo 'In coroutine' . PHP_EOL;
});

echo 'Hello world!' . PHP_EOL;

The go function returns a positive ID for the created coroutine. If Swoole cannot create the coroutine, Hypervel throws a CoroutineCreateException. The co function is an alias of go:

use function Hypervel\Coroutine\co;

$coroutineId = co(function () {
    // ...
});

You may also create a coroutine directly through the Coroutine class. The create and fork methods follow the same contract: they return a positive coroutine ID on success and throw CoroutineCreateException when creation fails:

use Hypervel\Coroutine\Coroutine;

$coroutineId = Coroutine::create(function () {
    // ...
});

Copying Coroutine Context

Child coroutines start with a fresh coroutine context by default:

use Hypervel\Context\CoroutineContext;

use function Hypervel\Coroutine\go;

go(function () {
    CoroutineContext::set('request_id', 'abc');

    go(function () {
        CoroutineContext::get('request_id'); // null
    });
});

When you enable context copying, Hypervel copies values from the current coroutine, such as the coroutine handling an HTTP request, console command, queued job, or test.

If the child coroutine needs the parent context, pass copyContext: true to copy all parent context keys:

go(function () {
    CoroutineContext::set('request_id', 'abc');

    go(function () {
        $requestId = CoroutineContext::get('request_id');
    }, copyContext: true);
});

You may also copy only specific keys:

go(function () {
    CoroutineContext::set('request_id', 'abc');
    CoroutineContext::set('user_id', 123);

    go(function () {
        $requestId = CoroutineContext::get('request_id');
        $userId = CoroutineContext::get('user_id'); // null
    }, copyContext: ['request_id']);
});

The Coroutine::fork method provides the same behavior when you prefer the class API:

use Hypervel\Context\CoroutineContext;
use Hypervel\Coroutine\Coroutine;

use function Hypervel\Coroutine\go;

go(function () {
    CoroutineContext::set('request_id', 'abc');

    Coroutine::fork(function () {
        $requestId = CoroutineContext::get('request_id');
    }, ['request_id']);
});

Objects stored directly as context values are shared by default. Values that implement Hypervel\Context\ReplicableContext are copied independently, while values that implement Hypervel\Context\NonCopyableContext are omitted. Hypervel does not inspect objects nested within arrays or other objects. See the coroutine context documentation for more information.

Package startup hooks may also propagate their own context into a fresh child. For example, Sentry and Telescope associate ordinary children with the parent's execution. Use detached background work when that association is unwanted.

Owning Child Startup

Package infrastructure may need to record ownership before a child's startup hooks run. The createOwned method accepts a wrapper that runs inside the child before its initial context is installed and before any startup hooks run. For example, count a child before creating it, then release that count even if the child is canceled during startup:

use Closure;
use Hypervel\Coroutine\Coroutine;
use Throwable;

$activeChildren = 0;
++$activeChildren;

try {
    $coroutineId = Coroutine::createOwned(
        function () {
            // Perform the child work...
        },
        function (Closure $run) use (&$activeChildren): void {
            try {
                $run();
            } finally {
                --$activeChildren;
            }
        },
    );
} catch (Throwable $exception) {
    --$activeChildren;

    throw $exception;
}

The wrapper must invoke $run exactly once. Outside that call it must not wait for I/O, channel data or capacity, or other work. Releases that cannot wait are allowed. Finalize the relevant ownership state before notifying waiters, since a notification can immediately run another coroutine. Keep work and cleanup that may wait inside the child callable. The wrapper's finally also runs if the child is canceled during startup, before the callable begins.

forkOwned accepts the same wrapper plus the context keys to copy, following the normal copying rules. Both methods return the child ID. If either method throws, including CoroutineCreateException or a context-copy failure from forkOwned, the wrapper has not run, so the caller still owns any resources it reserved.

Returning from the wrapper is not proof that the child has exited: deferred callbacks run afterward and may wait. Use Coroutine::join() or Coroutine::exists() when resource ownership depends on physical exit. A timed-out join does not terminate a child. For ordinary application tasks, prefer the wait, parallel, and WaitConcurrent APIs, which manage child ownership for you.

Detached Background Work

Background services can start without inheriting the request or tracing state of the caller that starts them. Pass detached: true to createOwned or forkOwned, using a callable and ownership wrapper as shown in the previous example:

use Hypervel\Coroutine\Coroutine;

$coroutineId = Coroutine::createOwned($callable, $wrapper, detached: true);

Startup hooks still run. The framework installs Coroutine::DETACHED_CONTEXT_KEY before the hooks run. Hooks that propagate parent context honor this marker by leaving explicitly installed child values intact and avoiding parent fallback. Detachment does not erase values explicitly copied by forkOwned. See the Sentry and Telescope documentation for their behavior in detached children.

The framework removes the marker after startup hooks and before the callable runs. A detached child may establish its own context, and children it creates, including from startup hooks, follow normal inheritance rules unless explicitly detached. Detachment controls context propagation; the caller still owns cancellation, joining, and resource cleanup.

Nested Coroutines

Coroutines may create other coroutines:

use function Hypervel\Coroutine\go;

go(function () {
    echo 'In parent coroutine' . PHP_EOL;

    go(function () {
        sleep(1);

        echo 'In nested coroutine' . PHP_EOL;
    });

    echo 'Back to parent coroutine' . PHP_EOL;
});

echo 'Main process' . PHP_EOL;

Each nested coroutine has its own coroutine ID and its own coroutine context. Application values are isolated unless explicitly copied; package startup hooks may also propagate execution context as described above.

Error Handling

A try / catch block only catches exceptions thrown inside the same coroutine. Calling go() creates a new coroutine and returns immediately, so a caller-side try / catch block will not catch exceptions thrown in the child coroutine:

use function Hypervel\Coroutine\go;

try {
    go(function () {
        throw new RuntimeException('Unable to process task.');
    });
} catch (Throwable $exception) {
    // This will not run...
}

Place the try / catch block inside the coroutine:

use function Hypervel\Coroutine\go;

go(function () {
    try {
        throw new RuntimeException('Unable to process task.');
    } catch (Throwable $exception) {
        report($exception);
    }
});

If you need to collect results or rethrow child coroutine exceptions in the parent coroutine, use parallel or wait.

Coroutine Cancellation

Hypervel uses Swoole\Coroutine\CanceledException as a terminal control-flow signal. Framework-owned operations preserve this exception instead of reporting it, retrying the canceled work, or converting it into an ordinary fallback value.

Most application code does not need special cancellation handling. If low-level application or package code catches Throwable to report, retry, wrap, or replace an operation failure, it should let cancellation escape first:

use Hypervel\Coroutine\Coroutine;
use Throwable;

try {
    $result = performOperation();
} catch (Throwable $exception) {
    if (Coroutine::causedByCancellation($exception)) {
        throw $exception;
    }

    report($exception);

    return null;
}

Coroutine::causedByCancellation also recognizes cancellation when a finally block throws another exception while unwinding it. Rethrowing preserves any cleanup error for the caller to report. A cancellation wrapped in Hypervel\Coroutine\Exceptions\ForeignCancellationException came from another coroutine, such as the owner of a shared operation this code was waiting for. If the chain reaches that exception before it reaches a cancellation, causedByCancellation returns false, so you can handle it as an ordinary failure. ChildCancellationException extends it for independently canceled children.

When work is shared, store its result or failure before waking waiting coroutines, and retain failures that later callers need to read. When passing cancellation to another coroutine, wrap it in ForeignCancellationException, or ChildCancellationException for an independently canceled child. Rethrow the original only in the canceled coroutine. Canceled work must not appear to have succeeded with an empty result.

Libraries may wrap cancellation in a more specific exception, such as Flysystem's UnableToReadFile. Check for cancellation before translating these exceptions, so callers do not treat canceled work as an ordinary application failure.

A direct CanceledException catch only matches cancellation thrown directly. Check the whole try block: if it also runs callbacks, listeners, or DB::releaseIdleConnections(), use causedByCancellation to recognize cancellation carried by another exception.

If a failure listener throws inside a catch block, its exception replaces the original. Dispatch from a finally block while rethrowing instead. PHP then attaches the original as the listener exception's previous exception, so causedByCancellation still detects it:

try {
    performOperation();
} catch (Throwable $exception) {
    try {
        throw $exception;
    } finally {
        event(new OperationFailed($exception));
    }
}

When collecting failures from several cleanup steps, or ignoring a cleanup failure to keep the original one, use Coroutine::preferCancellation($kept, $next). It keeps the first failure, replacing an ordinary failure when a later one carries this coroutine's cancellation.

Cleanup that does not wait should remain in finally as usual. Code that owns child coroutines should use wait, parallel, or WaitConcurrent so Hypervel can cancel active children when their parent is canceled.

Reporting Unhandled Exceptions

Hypervel catches unhandled exceptions thrown inside Coroutine::create, go, co, or Coroutine::fork and reports them through the application's exception handler when one is available.

You may disable this automatic reporting for the entire worker process using reportExceptions:

use Hypervel\Coroutine\Coroutine;

Coroutine::reportExceptions(false);

Warning

This setting remains active for the lifetime of the Swoole worker and affects every coroutine. Configure it during application boot or tests only.

Deferred Coroutine Cleanup

The Coroutine::defer method schedules a callback to run when the current coroutine exits. Deferred callbacks are useful for releasing resources that belong to a single coroutine:

use Hypervel\Coroutine\Coroutine;

use function Hypervel\Coroutine\go;

go(function () {
    Coroutine::defer(function () {
        echo 'Cleanup 1' . PHP_EOL;
    });

    Coroutine::defer(function () {
        echo 'Cleanup 2' . PHP_EOL;
    });

    echo 'Main logic' . PHP_EOL;
});

Deferred callbacks run in last-in, first-out order.

If a deferred callback throws an exception, Hypervel catches it and reports it through the application's exception handler when one is available. Add your own try / catch inside the deferred callback only when you want to handle the exception yourself:

go(function () {
    Coroutine::defer(function () {
        try {
            // ...
        } catch (Throwable $exception) {
            report($exception);
        }
    });
});

Note

Coroutine::defer() runs when the current coroutine exits. The Hypervel\Support\defer helper schedules a callback after the current HTTP response, console command, or queued job completes successfully.

Channels

Channels allow coroutines to communicate by passing values. Hypervel's channel implementation is available as Hypervel\Engine\Channel:

use Hypervel\Engine\Channel;

use function Hypervel\Coroutine\go;

$channel = new Channel(1);

go(function () use ($channel) {
    $channel->push('Hello from a coroutine.');
});

go(function () use ($channel) {
    echo $channel->pop();
});

The channel capacity controls how many values may be buffered. A push call waits when the channel is full, and a pop call waits when the channel is empty. Both methods accept a timeout in seconds:

$channel->push('value', timeout: 1.0);

$value = $channel->pop(timeout: 1.0);

When a push or pop fails, check the reason immediately, before yielding to another coroutine. If you need to send false as a value, wrap it in an array so you can distinguish it from a failed pop.

use Swoole\Coroutine\CanceledException;

if ($channel->pop(timeout: 1.0) === false) {
    if ($channel->wasCanceled()) {
        throw new CanceledException('Waiting for a value was canceled.');
    }

    if ($channel->timedOut()) {
        // No value arrived before the timeout...
    } elseif ($channel->isClosed()) {
        // The channel has closed and its buffer is empty...
    }
}

Use length() to get the number of buffered values and capacity() to get the maximum. You may also check isEmpty() or isFull(). To find out whether any coroutines are currently blocked trying to push or pop, use hasWaitingProducers() or hasWaitingConsumers(). These values can change when your coroutine yields.

Calling close() wakes waiting coroutines and prevents further pushes. You may still pop values that were buffered before the channel closed.

Waiting for Results

The wait Helper

The wait helper runs a closure inside a new coroutine and waits for its return value:

use function Hypervel\Coroutine\wait;

$result = wait(function () {
    return 'done';
});

You may pass a timeout in seconds:

$result = wait(function () {
    sleep(1);

    return 'done';
}, timeout: 2.0);

If no timeout is provided, wait will wait up to 10 seconds for the closure to finish.

The child coroutine receives a fresh context by default. You may copy all parent context keys, or only the keys the child needs, using the copyContext argument:

use Hypervel\Context\CoroutineContext;

$result = wait(function () {
    return CoroutineContext::get('request_id');
}, copyContext: true);

$result = wait(function () {
    return CoroutineContext::get('request_id');
}, copyContext: ['request_id']);

Copied values follow the same rules as go and Coroutine::fork.

If the closure throws an exception, wait rethrows it in the waiting coroutine after the child's deferred callbacks have finished.

If the child is canceled independently while its waiting parent remains active, wait throws Hypervel\Coroutine\Exceptions\ChildCancellationException. Its previous exception is the native cancellation, or the cleanup error if the child's cleanup threw while unwinding cancellation.

If the timeout is reached, Hypervel cancels the child by throwing Swoole\Coroutine\CanceledException inside it. Hypervel then gives the child up to 10 seconds to finish and run its deferred callbacks before throwing Hypervel\Coroutine\Exceptions\WaitTimeoutException in the waiting coroutine.

Code that catches the cancellation and keeps running may remain active after this 10-second cleanup period.

If the waiting code must not continue while the child remains active, pass waitForChildTermination: true:

$result = wait(function () {
    // ...
}, timeout: 2.0, waitForChildTermination: true);

The requested timeout still cancels the child. If the child stops within the cleanup period, wait throws WaitTimeoutException as usual. If the child remains active after that period, wait continues waiting until it exits and then throws ChildTerminationTimeoutException. This exception extends WaitTimeoutException, so an existing catch for WaitTimeoutException handles both cases.

The same holds when the waiting coroutine is itself canceled: wait cancels the child, waits until it has exited, including any cleanup that waits on I/O, and then lets the cancellation continue. Without waitForChildTermination, the cancellation continues at once while the child finishes on its own.

Warning

Waiting for child termination has no secondary timeout. A child that catches cancellation and does not finish can keep the waiting coroutine blocked indefinitely.

You may also use the Waiter class directly:

use Hypervel\Coroutine\Waiter;

$waiter = new Waiter(timeout: 10.0);

$result = $waiter->wait(function () {
    return 'done';
});

The Waiter::wait method accepts the same waitForChildTermination argument as the helper.

Wait Groups

A WaitGroup allows one coroutine to wait until a group of other coroutines finishes:

use Hypervel\Coroutine\WaitGroup;

use function Hypervel\Coroutine\go;

$waitGroup = new WaitGroup();

foreach ($jobs as $job) {
    $waitGroup->add();

    go(function () use ($job, $waitGroup) {
        try {
            $job->handle();
        } finally {
            $waitGroup->done();
        }
    });
}

$waitGroup->wait();

You may initialize the counter in the constructor:

$waitGroup = new WaitGroup(count($jobs));

The wait method accepts a timeout in seconds and returns true when all work has completed or false when the wait timed out:

if (! $waitGroup->wait(timeout: 5.0)) {
    // The wait timed out...
}

You may inspect the current counter using the count method:

$count = $waitGroup->count();

Barriers

A Barrier waits for every coroutine that captures it to finish:

use Hypervel\Coroutine\Barrier;
use Hypervel\Coroutine\Coroutine;

$barrier = Barrier::create();

foreach ($jobs as $job) {
    // Capturing the barrier allows Barrier::wait() to observe this coroutine.
    Coroutine::create(function () use ($barrier, $job) {
        $job->handle();
    });
}

Barrier::wait($barrier);

Running Work in Parallel

The parallel helper runs multiple callbacks concurrently and waits for all of them to finish. Results are returned using the keys from the input array:

use function Hypervel\Coroutine\parallel;

$results = parallel([
    'users' => fn () => countUsers(),
    'orders' => fn () => countOrders(),
]);

$results['users'];
$results['orders'];

You may limit the number of callbacks that run at the same time using the second argument:

$results = parallel($callbacks, concurrent: 10);

By default, child coroutines receive a fresh context. You may copy all parent context keys or only specific keys using the copyContext argument:

$results = parallel($callbacks, copyContext: true);

$results = parallel($callbacks, copyContext: ['request_id']);

If any callback throws an exception, parallel waits for every callback to finish and then throws Hypervel\Coroutine\Exceptions\ParallelExecutionException. The exception contains the successful results and the throwables captured from failed callbacks:

use Hypervel\Coroutine\Exceptions\ParallelExecutionException;

try {
    parallel($callbacks);
} catch (ParallelExecutionException $exception) {
    $results = $exception->getResults();

    $throwables = $exception->getThrowables();
}

An independently canceled child is recorded as Hypervel\Coroutine\Exceptions\ChildCancellationException. Its previous exception is the native cancellation, or the cleanup error if the child's cleanup threw while unwinding cancellation.

Limiting Parallel Work

For more control, use the Parallel class directly:

use Hypervel\Coroutine\Parallel;

$parallel = new Parallel(concurrent: 5, copyContext: true);

$parallel->add(fn () => countUsers(), 'users');
$parallel->add(fn () => countOrders(), 'orders');

$results = $parallel->wait();

The count method returns the number of registered callbacks:

$count = $parallel->count();

The clear method removes all registered callbacks, results, and captured throwables:

$parallel->clear();

Inspecting Parallel Failures

If you do not want wait to throw when one or more callbacks fail, pass throw: false:

$results = $parallel->wait(throw: false);

if ($parallel->hasFailures()) {
    $throwables = $parallel->getThrowables();
}

You may retrieve the number of failed callbacks using failedCount:

$failedCount = $parallel->failedCount();

Limiting Concurrent Coroutines

The Concurrent class limits how many child coroutines may run at the same time:

use Hypervel\Coroutine\Concurrent;

$concurrent = new Concurrent(10);

foreach ($jobs as $job) {
    $concurrent->create(function () use ($job) {
        $job->handle();
    });
}

When the limit is reached, create waits until an existing child coroutine finishes and releases a slot.

You may inspect the current limit and number of running coroutines:

$limit = $concurrent->getLimit();

$runningCoroutineCount = $concurrent->getRunningCoroutineCount();

You may use the isFull method to determine if the concurrency limit has been reached and the isEmpty method to determine if all child coroutines have finished:

if ($concurrent->isFull()) {
    // The concurrency limit has been reached...
}

if ($concurrent->isEmpty()) {
    // No child coroutines are currently running...
}

If you need to wait for capacity without starting another coroutine, you may use the waitForAvailableSlot method. The method returns false when the timeout is reached:

if (! $concurrent->waitForAvailableSlot(timeout: 1.0)) {
    // No slot became available within one second...
}

This method only waits until a slot becomes available; it does not reserve the slot after returning. A later create or fork call will wait again if another producer claims the available slot first.

You may use fork instead of create when child coroutines should receive a copy of the parent context:

$concurrent->fork(function () {
    // ...
}, ['request_id']);

Waiting for Limited Coroutines

The WaitConcurrent class combines concurrency limiting with a wait method:

use Hypervel\Coroutine\WaitConcurrent;

$concurrent = new WaitConcurrent(10);

foreach ($jobs as $job) {
    $concurrent->create(function () use ($job) {
        $job->handle();
    });
}

$concurrent->wait();

The wait method accepts a timeout in seconds and returns true when all child coroutines have completed or false when the wait timed out:

if (! $concurrent->wait(timeout: 5.0)) {
    // The wait timed out...
}

A successful wait includes each child's deferred cleanup, so resources held by a child are released before the method returns.

You may cancel every currently active child body using the cancel method:

$concurrent->cancel();

Cancellation does not wait for child cleanup to finish. A child whose body has completed and is only running deferred cleanup is no longer active and is not interrupted. Each call targets the child bodies active at that time.

Locks

Mutexes

The Mutex class ensures that only one coroutine at a time may hold a lock for a given string key:

use Hypervel\Coroutine\Mutex;

if (Mutex::lock('reports')) {
    try {
        // Only one coroutine may run this block for the key...
    } finally {
        Mutex::unlock('reports');
    }
}

The lock and unlock methods both accept timeouts in seconds:

if (! Mutex::lock('reports', timeout: 1.0)) {
    // The lock could not be acquired...
}

if (! Mutex::unlock('reports', timeout: 1.0)) {
    // The lock was not released...
}

The mutex does not track coroutine ownership. Each successful lock call must be matched by exactly one unlock call from the coroutine that acquired it.

The clear method closes the current mutex channel and cancels any waiting acquisitions. Use it only to explicitly cancel and reset a key, not for normal release:

Mutex::clear('reports');

Lockers

The Locker class allows one coroutine to perform work while other coroutines wait for it to finish. The first coroutine to call lock for a key receives true. Other coroutines wait until the key is unlocked and then receive false:

use Hypervel\Coroutine\Locker;

if (Locker::lock('warm-cache')) {
    try {
        rebuildCache();
    } finally {
        Locker::unlock('warm-cache');
    }
} else {
    // Another coroutine rebuilt the cache...
}

A waiting coroutine may limit how many seconds it will wait using the timeout argument. If the key is not unlocked in time, lock throws a Hypervel\Coroutine\Exceptions\WaitTimeoutException. If the waiting coroutine is canceled, lock throws a Swoole\Coroutine\CanceledException. Either way, the owner keeps its lock and the other coroutines keep waiting:

use Hypervel\Coroutine\Exceptions\WaitTimeoutException;

try {
    if (Locker::lock('warm-cache', timeout: 2.0)) {
        try {
            rebuildCache();
        } finally {
            Locker::unlock('warm-cache');
        }
    }
} catch (WaitTimeoutException $exception) {
    // The cache was not rebuilt within two seconds...
}

A waiting coroutine receives false even when the owner's work failed. When that work may fail, waiting coroutines should check for the result and call lock again if it is missing. One of them becomes the next owner and retries the work while the others wait. Since the previous owner may finish between a coroutine's check and its call to lock, a new owner should check again before doing the work:

while (($report = Cache::get('report')) === null) {
    if (Locker::lock('report')) {
        try {
            if (Cache::get('report') === null) {
                Cache::put('report', buildReport());
            }
        } finally {
            Locker::unlock('report');
        }
    }
}

Advanced Coroutine APIs

The Coroutine class provides additional methods for advanced use cases:

use Hypervel\Coroutine\Coroutine;

Coroutine::sleep(0.1);

$joined = Coroutine::join([$firstCoroutineId, $secondCoroutineId], timeout: 5.0);

$statistics = Coroutine::stats();

$coroutineExists = Coroutine::exists($coroutineId);

$coroutineIds = Coroutine::list();

The join method waits for the supplied child coroutine IDs to finish. You may include IDs for coroutines that have already finished.

A false result may mean that all supplied coroutines had already finished or that the timeout elapsed. If the caller is canceled during the wait, join throws a CanceledException.

Use joinUninterruptibly when cleanup must wait for children to exit even if the caller is canceled. It waits until the children exit or the original timeout expires, then throws the caller's first cancellation. Without cancellation, it returns true if none of the supplied coroutines are still running. As with join, a timeout of zero or less waits without a deadline.

The afterCreated method registers a callback that runs during child startup for Coroutine::create, fork, createOwned, and forkOwned, as well as helpers such as go and co:

Coroutine::afterCreated(function () {
    // ...
});

Warning

These callbacks remain registered for the lifetime of the Swoole worker. Register them during application boot or tests only. They run synchronously during child startup and must not perform work that suspends the coroutine.

Hooks that copy state from the parent must check CoroutineContext::has(Coroutine::DETACHED_CONTEXT_KEY) and skip parent fallback when it is present. Preserve explicitly installed child values and any isolation they need. The marker remains available to every startup hook and is removed before the application callable runs. See detached background work.

The flushState method clears coroutine settings and callbacks stored for the current worker:

Coroutine::flushState();

Warning

flushState is intended for tests and package cleanup. Calling it during normal request handling clears coroutine settings and callbacks for every coroutine in the worker.

Common Pitfalls

Hypervel workers stay alive and may run many coroutines at the same time. Do not store request-specific state in global variables, mutable static properties, or shared singleton object properties. Store it in coroutine context instead.

Use Coroutine::defer() for cleanup that belongs to one coroutine. Use Hypervel\Support\defer for callbacks that should run after a successful HTTP response, console command, or queued job.

Prefer the Concurrency facade or the parallel helper when the parent coroutine needs results or exceptions from child coroutines. Use go, co, Coroutine::create, or Concurrent when a child may run independently and its exceptions may be reported instead of returned to the parent.

Swoole can make most stream-based I/O operations yield to other coroutines while they wait. Some PHP extensions cannot be hooked and will block the entire worker process. For CPU-intensive work or extensions that cannot yield, you should run the work in a separate process.

Credits

Hypervel Coroutine began as a port of Hyperf Coroutine and has been adapted for Hypervel's framework architecture and coroutine runtime.