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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.