2 Replies - 588 Views - Last Post: 14 May 2013 - 07:57 AM Rate Topic: -----

#1 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Can I parallellize this foreach loop in PHP?

Posted 14 May 2013 - 07:32 AM

Here's my snippet:


    $items = getSomeItems();
    $results = array();
    
    foreach ($items as $index => $value) {
        $valueA = getValueA($value); // 2 minute process.
        $valueB = getValueB($value); // 2 minute process.
        $valueC = getValueC($value); // 2 minute process.
        $results[] = array('a' => $valueA, 'b' => $valueB, 'c' => $valueC, )
    }

    return $results;


Is there some way to paralellize this foreach loop? I don't care the order in with the arrays are added to `$results`, I order them in SQL anyways.

Can I do something like?

    parallel-foreach ($items as $index => $value) {
        $valueA = getValueA($value); // 2 minute process.
        $valueB = getValueB($value); // 2 minute process.
        $valueC = getValueC($value); // 2 minute process.
        $results[] = array('a' => $valueA, 'b' => $valueB, 'c' => $valueC, )
    }


C# has a similar idea in Parallel.Foreach. I'm looking for something similar in PHP.

This post has been edited by Sergio Tapia: 14 May 2013 - 07:32 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Can I parallellize this foreach loop in PHP?

#2 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 9096
  • View blog
  • Posts: 34,155
  • Joined: 12-June 08

Re: Can I parallellize this foreach loop in PHP?

Posted 14 May 2013 - 07:41 AM

Typically you wouldn't expect a scripting language like php to have multithreading, but there are some tools like pthreads.

Outside of that you need to hunt down some extra libraries or some third party bit to bolt into your setup.
Was This Post Helpful? 0
  • +
  • -

#3 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6058
  • View blog
  • Posts: 23,496
  • Joined: 23-August 08

Re: Can I parallellize this foreach loop in PHP?

Posted 14 May 2013 - 07:57 AM

Some sort of message queuing system, like AMQP or Gearman might work.

Quote

pthreads was, and is, an experiment with pretty good results. Any of its limitations or features may change at any time; that is the nature of experimentation. Its limitations - often imposed by the implementation - exist for good reason; the aim of pthreads is to provide a useable solution to multi-tasking in PHP at any level. In the environment which pthreads executes, some restrictions and limitations are necessary in order to provide a stable environment.


Hmmm. Sounds scary for production.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1