ComponentsThreadPool::getWorkerCount()

ThreadPool::getWorkerCount() ​

(PHP 8.6+, True Async 1.0)

php
public ThreadPool::getWorkerCount(): int

Returns the number of worker threads running in the pool right now. It starts at the $workers argument passed to new ThreadPool() and drops as workers exit.

Return Value ​

int — number of worker threads running now. A worker leaves the count when its thread returns, so a closed pool reports 0 once its workers have drained, and a pool that lost a thread reports one less than it was constructed with.

Examples ​

Example #1 Confirming worker count ​

php
<?php

use Async\ThreadPool;
use function Async\spawn;

spawn(function() {
    $pool = new ThreadPool(workers: 4);

    echo $pool->getWorkerCount(), "\n"; // 4

    $pool->close();
});

Example #2 Sizing the pool to available CPU cores ​

php
<?php

use Async\ThreadPool;
use function Async\spawn;
use function Async\await;

spawn(function() {
    $cores = (int) shell_exec('nproc') ?: 4;
    $pool  = new ThreadPool(workers: $cores);

    echo "Pool created with ", $pool->getWorkerCount(), " workers\n";

    $futures = [];
    for ($i = 0; $i < $cores * 2; $i++) {
        $futures[] = $pool->submit(fn() => 'done');
    }
    foreach ($futures as $f) {
        await($f);
    }

    $pool->close();
});

See Also ​