Reputation: 21
Hello AMPHP community,
I am new to AMPHP and am looking for a simple code example for running an asynchronous process without the main thread waiting for asynchronous feedback.
For example, imagine this use case: running a background process that logs page visit data into a database without taking up the main thread time used to display an HTML page.
Does a code example like this already exist within the AMPHP community? Could an example be shared or created?
The introductory code provided by AMPHP is very clear; however, it only includes an example of a process that communicates with the main thread via ->await();
ie.
$future1 = async(function ()
{
echo 'Hello ';
// delay() is a non-blocking version of PHP's sleep() function,
// which only pauses the current fiber instead of blocking the whole process.
delay(2);
echo 'the future! ';
});
$future2 = async(function ()
{
echo 'World ';
// Let's pause for only 1 instead of 2 seconds here,
// so our text is printed in the correct order.
delay(1);
echo 'from ';
});
// Our functions have been queued, but won't be executed until the event-loop gains control.
echo "Let's start: ";
// Awaiting a future outside a fiber switches to the event loop until the future is complete.
// Once the event loop gains control, it executes our already queued functions we've passed to async()
$future1->await();
$future2->await();
I have explored or tried to explore several parallel environments, but appreciate the rapid and relatively hassle free environment provided by AMPHP.
Upvotes: 0
Views: 91