Jump to content

assign a method to an array


Vadimbr

Recommended Posts

Hi,

I'm trying to implement multithreading using Threadi

https://github.com/danielpoe/Threadi

 

Here is a sample code to what I'm trying to do:

require_once(dirname(__FILE__).'/../Loader.php');

class Worker {
public function fetchAWebsite($url) {
	$content = file_get_contents($url);
	return "fetched website $url - lenght ".strlen($content).PHP_EOL;
}
}
$worker = new Worker();
$startTime = microtime(TRUE);
$thread1 = Threadi_ThreadFactory::getReturnableThread(array($worker,'fetchAWebsite'));
$thread1->start('http://www.google.de'); 
$thread2 = Threadi_ThreadFactory::getReturnableThread(array($worker,'fetchAWebsite'));
$thread2->start('http://www.aoemedia.de');

$joinPoint = new Threadi_JoinPoint($thread1, $thread2);
$joinPoint->waitTillReady();

echo $thread1->getResult();
echo $thread2->getResult();
echo "Time needed in seconds: ". ( microtime(TRUE)-$startTime).PHP_EOL;

 

The problem that I'm having is that I need to call each thread separately by name. Creating 10 or more threads makes a lot redundant code.

How can I assign  Threadi_ThreadFactory::getReturnableThread to an indexed variable(array) ?

 

I tried something in this lines but with no success:

$hArr = array();//handle array

for ($i=0;$i<THREADS;$i++) {
         $thread[$i] = Threadi_ThreadFactory::getReturnableThread(array($worker,'fetchAWebsite'));
         $thread[$i]->start($site[$i]); 
         array_push($hArr,$thread[$i]-);
}
$joinPoint = new Threadi_JoinPoint($hArr);
$joinPoint->waitTillReady();

 

What I'm doing wrong?

Thanks

Link to comment
Share on other sites

It should be as easy as this

$threads[] = Threadi_ThreadFactory::getReturnableThread(array($worker,'fetchAWebsite'));
$threads[0]->start('http://www.google.de');

$threads[] = Threadi_ThreadFactory::getReturnableThread(array($worker,'fetchAWebsite'));
$threads[1]->start('http://www.aoemedia.de');

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.