Menu
Reference
- Manticore\Ds
- Async
- Classes
- AggregateError
- CancellationToken
- CancelledException
- Channel
- ChannelClosedException
- Context
- DeadlockException
- Mutex
- Once
- Pool
- Received
- SelectCase
- Selected
- Semaphore
- Settled
- Task
- TaskGroup
- TimeoutException
- Functions
- async()
- awaitAll()
- awaitAllSettled()
- awaitAny()
- channel()
- delay()
- dump()
- dumpOn()
- failure()
- group()
- mapConcurrent()
- mapSettled()
- readFile()
- select()
- selectNow()
- selectWithin()
- shield()
- shutdownOn()
- spawn()
- stats()
- timeout()
- watchdog()
- writeFile()
- Http
- Http\WebSocket
- Buffer
- Process
- Io\Poll
- Manticore\Sapi
- Ffi
mapConcurrent()
function
function mapConcurrent(array $items, callable $fn, int $limit): array
Map $fn over $items with at most $limit calls running at once.
The everyday "fetch 1000 URLs, 10 at a time". Results are keyed like $items; the first failure cancels the rest and propagates (fail-fast, like awaitAll()).
$pages = Async\mapConcurrent($urls, fn($u) => file_get_contents($u), 10);Parameters
$itemsmixed[]$fncallable- called as
$fn($item, $key)for each item $limitint- maximum calls in flight; values below 1 are raised to 1
Returns
mixed[] — the results, keyed like $items
Throws
- \Throwable
- the first failure
Example
use function Async\async;
use function Async\delay;
use function Async\mapConcurrent;
$inFlight = 0;
$peak = 0;
$squares = async(function () use (&$inFlight, &$peak) {
// Square five numbers, never more than two at a time.
return mapConcurrent([1, 2, 3, 4, 5], function (int $n) use (&$inFlight, &$peak) {
$inFlight++;
$peak = max($peak, $inFlight);
delay(0.01);
$inFlight--;
return $n * $n;
}, 2);
});
echo implode(",", $squares), "\n";
echo "peak in flight: $peak\n";Output
1,4,9,16,25
peak in flight: 2See also: mapSettled, Semaphore