1

Can someone help me please, to use fiber on a loop like pcntl_fork to process data in parallel, Here is the code for converting to fiber, Thanks.

`$names = array('A','B','C','D','E');
$childs = array();

for ($i=0; $i < count($names) ; $i++) {

    $pid = pcntl_fork();
    if($pid == -1)
        die('Could not fork \n');

    if ($pid) {
        //echo 'parent \n';
        $childs[] = $pid;
    } else {
        // Sleep $i+1 (s). The child process can get this parameters($i).
        get_data_function($names[$i]);
        sleep(1);                       

        // The child process needed to end the loop.
        exit();
    }       
        
    
}
while(count($childs) > 0) {
    foreach($childs as $key => $pid) {
        $res = pcntl_waitpid($pid, $status, WNOHANG);
        
        // If the process has already exited
        if($res == -1 || $res > 0)
            unset($childs[$key]);
    }
    
    sleep(1);
}`

I want the function get_data_function() to run in parallel on all names like pcnt_fork pcnt_fork: make the loop asynchronous in the end I want to convert the above algorithm which uses pcntl_fork, by the new feature fibers in php8

Notice: the algorithm works very well with pcntl_fork in multithread

  • 1
    `pcntl_fork` and multithreading are two different things. `pcntl_fork` uses `fork()` to create an entirely new process. – Marco Jan 06 '23 at 16:14
  • Fibers are also neither threads nor processes, but simply asyncronous execution within a single thread/process. – Sammitch Jan 06 '23 at 20:15

0 Answers0