Monday, 1 May 2023

Examples of synchronous and asynchronous code in PHP

1. Using Synchronous 

The program waits for the current task to finish before starting the next task

<?php
$start = microtime(true);
echo 'start' . PHP_EOL;

function run() {
echo 'before' . PHP_EOL;
usleep(3000000); // equivalent of setTimeout in Node.js
echo 'wait 3 seconds' . PHP_EOL;
echo 'after' . PHP_EOL;
}

run();

echo 'end' . PHP_EOL;
$end = microtime(true);
$time_taken = $end - $start;
echo "Time taken: " . number_format($time_taken, 5) . " seconds";

output

start
before
wait 3 seconds
after
end
Time taken: 3.00017 seconds

Or

<?php
$start = microtime(true);
echo 'start' . PHP_EOL;

function run() {
echo 'before' . PHP_EOL;
// usleep(3000000); // equivalent of setTimeout in Node.js
echo 'wait 3 seconds' . PHP_EOL;
echo 'after' . PHP_EOL;
}

run();

echo 'end' . PHP_EOL;
$end = microtime(true);
$time_taken = $end - $start;
echo "Time taken: " . number_format($time_taken, 5) . " seconds";

output

start
before
wait 3 seconds
after
end
Time taken: 0.00004 seconds

2. Using Asynchronous 

The program can continue to execute while waiting for a task to complete

You have to install ReactPHP to use asynchronous in PHP

Thank you 


No comments:

Post a Comment

Golang Advanced Interview Q&A