ComponentiThreadPool::getWorkerCount()

ThreadPool::getWorkerCount()

(PHP 8.6+, True Async 1.0)

php
public ThreadPool::getWorkerCount(): int

Restituisce il numero di thread worker nel pool. Questo valore è fissato al momento della costruzione e non cambia durante la vita del pool. È uguale all'argomento $workers passato a new ThreadPool().

Valore restituito

int — numero di thread worker (impostato nel costruttore).

Esempi

Esempio #1 Verifica del numero di worker

php
<?php

use Async\ThreadPool;
use function Async\spawn;

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

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

    $pool->close();
});

Esempio #2 Dimensionamento del pool in base ai core CPU disponibili

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 creato con ", $pool->getWorkerCount(), " worker\n";

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

    $pool->close();
});

Vedere anche