John Davidson

php - I want to run three loops by parallel processing Without using Pthreads?

0 comments
Message:


look at my script, if i run one loop, it takes 3 sec, right? ( each loop has a sleep(1) )
So running 3 loops will take about 9 sec.
I want this:
I run parallel all 3 loops, to be finished in total 3 sec.
I want to perform it without using threads and pthreads php


name: 0 started at: 15:51:43
name: 1 started at: 15:51:44
name: 2 started at: 15:51:45




day: 0 started at: 15:51:43
day: 1 started at: 15:51:44
day: 2 started at: 15:51:45




week: 0 started at: 15:51:43
week: 1 started at: 15:51:44
week: 2 started at: 15:51:45


this is my code


<?php

function getResult(){


echo "<br>";
for($i=0; $i < 3; $i++){
echo "name: " . $i . " started at:" . date('h:i:s') . "<br>";
sleep(1);
}
echo"<hr>";
for($i=0; $i < 3; $i++){
echo "day: " . $i . " started at:" . date('h:i:s') . "<br>";
sleep(1);
}
echo"<hr>";

for($i=0; $i < 3; $i++){
echo "week: " . $i . " started at:" . date('h:i:s') . "<br>";
sleep(1);
}
echo `enter code here`"<hr>";


getResult();

?>

That does not work. I want to run this code in parallel.
I want to run three different loops at the same time.



My Answer:
One way to achieve parallel processing in PHP without using threads or pthreads is to use the `exec()` function to run separate PHP scripts in the background. Each script will handle one of the loops and run concurrently with the main script.

Here's an example of how you can modify your code to achieve parallel processing:

php

function runScript($script) {
$command = "php $script.php";
exec($command . " > /dev/null 2>&1 &");
}

runScript("name");
runScript("day");
runScript("week");

?>


Create three separate PHP scripts named `name.php`, `day.php`, and `week.php` with the following code:

php

for($i=0; $i < 3; $i++){
echo "name: " . $i . " started at:" . date('h:i:s') . "
";
sleep(1);
}

?>


php

for($i=0; $i < 3; $i++){
echo "day: " . $i . " started at:" . date('h:i:s') . "
";
sleep(1);
}

?>


php

for($i=0; $i < 3; $i++){
echo "week: " . $i . " started at:" . date('h:i:s') . "
";
sleep(1);
}

?>


When you run the main script, it will execute the three separate scripts in the background, allowing them to run concurrently and finish in a shorter total time.

Rate this post

5 of 5 based on 6377 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us