PHP code example of joshdifabio / resource-pool

1. Go to this page and download the library: Download joshdifabio/resource-pool library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

joshdifabio / resource-pool example snippets


function sendRequest($httpRequest) : PromiseInterface {
    // this would probably be something like Guzzle or React/HttpClient
}

foreach (getThousandsOfRequests() as $request) {
    sendRequest($request)->then(function ($response) {
        // the response came back!
    });
}

// thousands of requests have been initiated concurrently

$pool = new \ResourcePool\Pool(5);

foreach (getThousandsOfRequests() as $request) {
    // to() will invoke a function and then release the allocated resources once it's done
    $pool->allocateOne()->to('sendRequest', $request)->then(function ($response) {
        // the response came back!
    });
}

// five requests are running; the rest are queued and will be sent as others complete

$pool->allocate(5)->to(function () {
    // this task 

$pool->allocateAll()->to(function () {
    // this 

// call then() instead of to() to work with the allocation directly
$pool->allocate(2)->then(function ($allocation) {
    // two things which need to run at the same time
    firstThing()->done([$allocation, 'releaseOne']);
    secondThing()->done([$allocation, 'releaseOne']);
});

try {
    $allocation = $pool->allocate(2)->now();
} catch (\RuntimeException $e) {
    // throws a \RuntimeException if the pool cannot allocate two resources
}

$pool = new \ResourcePool\Pool(1);
$allocation = $pool->allocate(2)->force();
$pool->getUsage(); // 2
$pool->getAvailability(); // 0
$allocation->releaseAll();
$pool->getAvailability(); // 1

$pool->whenNextIdle(function () {
    // the pool is idle!
});

$pool->setSize(100);

$pool->getUsage();

$pool->getAvailability();