note 125640 added to book.pthreads
| From: | meadowsjared at gmail dot com | Date: | Tue, 29 Dec 2020 16:49:12 +0000 |
| Subject: | note 125640 added to book.pthreads | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-216040@lists.php.net to get a copy of this message | ||
In this example, it shows how to use a threaded with a pool to get an array of results, using
pThreads v3.2.1 and php 7.3.23
<?php
class TestWork extends Threaded {
//updated version that works with pThreads v3.2.1 and php 7.3.23
protected $complete;
//$pData is the data sent to your worker thread to do it's job.
public function __construct($pData) {
//transfer all the variables to local variables
$this->complete = false;
$this->testData = $pData;
}
//This is where all of your work will be done.
public function run() {
usleep(2000000); //sleep 2 seconds to simulate a large job
$this->complete = true;
}
public function isDone() {
return $this->complete;
}
}
class ExamplePool extends Pool {
public $data = array(); // used to return data after we're done
private $numTasks = 0; // counter used to know when we're done
/**
* override the submit function from the parent
* to keep track of our jobs
*/
public function submit(Threaded $task) {
$this->numTasks++;
parent::submit($task);
}
/**
* used to wait until all workers are done
*/
public function process() {
// Run this loop as long as we have
// jobs in the pool
while (count($this->data) < $this->numTasks) {
$this->collect(function (TestWork $task) {
// If a task was marked as done
// collect its results
if ($task->isDone()) {
$tmpObj = new stdclass();
$tmpObj->complete = $task->complete;
//this is how you get your completed data back out [accessed by $pool->process()]
$this->data[] = $tmpObj;
}
return $task->isDone();
});
}
// All jobs are done
// we can shutdown the pool
$this->shutdown();
return $this->data;
}
}
$pool = new ExamplePool(3);
$testData = 'asdf';
for($i=0;$i<5;$i++) {
$pool->submit(new TestWork($testData));
}
$retArr = $pool->process(); //get all of the results
echo '<pre>';
print_r($retArr); //return the array of results (and maybe errors)
echo '</pre>';
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.159.165 (proxied: 174.134.27.185)
----
Manual Page -- http://php.net/manual/en/book.pthreads.php
Edit -- https://master.php.net/note/edit/125640
Del: integrated -- https://master.php.net/note/delete/125640/integrated
Del: useless -- https://master.php.net/note/delete/125640/useless
Del: bad code -- https://master.php.net/note/delete/125640/bad+code
Del: spam -- https://master.php.net/note/delete/125640/spam
Del: non-english -- https://master.php.net/note/delete/125640/non-english
Del: in docs -- https://master.php.net/note/delete/125640/in+docs
Del: other reasons-- https://master.php.net/note/delete/125640
Reject -- https://master.php.net/note/reject/125640
Search -- https://master.php.net/manage/user-notes.php