2

I've been learning to program in PHP and made an application which makes several independent things, the problem is it takes about 20-30 seconds to finish the task, because the code is executed sequentially.

I was reading and found out that there are no threads in php, is there any way to get around?

Edit: added information:

Basically, my application will seek information from news, weather, etc. (with file_get_contents($url)), but performs the functions sequentially, in other words, first fetches the news, then information about weather, and successively, instead of running it all at the same time .

Thom Wiggers
  • 6,938
  • 1
  • 39
  • 65

4 Answers4

3

Use some kind of job-queuing software like Gearman or RabbitMQ, then - put those ops in the consumer.

eRIZ
  • 1,477
  • 16
  • 32
2

use CURL_MULTI instead, much faster. http://php.net/manual/en/function.curl-multi-init.php

It will reduce the loading \ processing time noticeably if you are reading numerous pages.

Oleg Belousov
  • 9,981
  • 14
  • 72
  • 127
-1

You could also try to hack in some threading behaviour by launching different requests to your webserver at the same time. For instance, your index.php would serve a simple page, which contains a number of AJAX calls to, say, fetchNews.php and fetchWeather.php. These requests would then be run asynchronously, in parallel, by the browser, and you'd circumvent phps limit on threading by just launching different webserver requests.

Thom Wiggers
  • 6,938
  • 1
  • 39
  • 65
-3

You mention that you're doing a bunch of file_get_contents($url)-calls. These are pretty slow. It would be a huge timesaver if instead of pulling these files in every time you load the page, you cache them to local storage and read them from there: that would be almost instant. Of course, you'd need to keep in mind how fresh you need your information.

For instance you could run a cron job that fetches these files every minute or so. Then you could have your website render this fetched information: the information would only be max 1 minute + the time it takes to run that script out of date.

Thom Wiggers
  • 6,938
  • 1
  • 39
  • 65