note 129800 added to language.fibers

From: Date: Thu, 10 Oct 2024 06:06:46 +0000
Subject: note 129800 added to language.fibers
Groups: php.notes 
Request: Send a blank email to php-notes+get-221587@lists.php.net to get a copy of this message
From my observation you will not get any parallel benefit from Fibers unless you Fiber::suspend() after some kind of system or server call. In other words, if you were to Fiber::suspend() within the function passed to new Fiber before $t = microtime(true), as opposed to after it, the code below would take one thousand seconds, instead of just over one second. Also, note that main thread code will not run in parallel unless all Fibers are started before any of the Fibers are resumed. <?php // 1000 Fibers that take one second individually can take about one second total along with the main thread in parallel $entireExecutionStartTime = microtime(true); function createTimeoutFibers(int $count = 1, float $milliseconds = 1000):array{ $a = []; $cF = function() use ($milliseconds):Fiber{ $f = new Fiber(function() use ($milliseconds){ $t = microtime(true); Fiber::suspend(); while(($q = microtime(true)-$t) < $milliseconds/1000){} // wait return $q; }); $f->start(); return $f; }; for($i=0; $i<$count; $i++){ $a[] = $cF(); } return $a; } // create an array of 1000 Fibers that each wait one second $a = createTimeoutFibers(1000); $fiberExecutionTimes = []; // wait one second on the main thread - to receive a main thread benefit this must occur after all FiberInstance->start()s and before any FiberInstance->resume()s $m = microtime(true); while(microtime(true)-$m < 1){} foreach($a as $f){ while(!$f->isTerminated()){ $f->resume(); } $fiberExecutionTimes[] = $f->getReturn(); } $entireExecutionTime = microtime(true)-$entireExecutionStartTime; // easy to read output in $test $test = '$fiberExecutionTimes = ['.join(', ', $fiberExecutionTimes).']; $entireExecutionTime = '.$entireExecutionTime.';'; ?> ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.84.18 (proxied: 24.19.197.14) ---- Manual Page -- https://php.net/manual/en/language.fibers.php Edit -- https://main.php.net/note/edit/129800 Del: integrated -- https://main.php.net/note/delete/129800/integrated Del: useless -- https://main.php.net/note/delete/129800/useless Del: bad code -- https://main.php.net/note/delete/129800/bad+code Del: spam -- https://main.php.net/note/delete/129800/spam Del: non-english -- https://main.php.net/note/delete/129800/non-english Del: in docs -- https://main.php.net/note/delete/129800/in+docs Del: other reasons-- https://main.php.net/note/delete/129800 Reject -- https://main.php.net/note/reject/129800 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221587) next »