-1

The problem is simple. I want to continuously execute a function while I wait for another task to finish, like in this silly example:

#!/usr/bin/env php
<?php

$timer = function() {
  static $seconds = 0;
  while(1) {
    sleep(1);
    echo "\r", $seconds++;
  }
}

$timer(); // I want to run this in parallel

$service = new Service();
$response = $service->goGetSomething('from far far away');

// I want to kill the timer here

I do parallel processing with other languages all the time, but have no idea how to achieve this with PHP. Requirements:

  • The simplest solution as possible, ++ if you use only PHP extensions enabled by default.
  • I don't need Windows support :)

PS: Don't tell me to use nodejs or [your-favorite-language] that doesn't suck :)

marcio
  • 10,002
  • 11
  • 54
  • 83
  • I don't like the answers from the other question you pointed out, the only good answer requires pthreads extension. Sad how we can't ask anything on stack overflow anymore. – marcio Jun 29 '14 at 03:50
  • 1
    maybe this could shed some light, i used this once in my projects [link](http://www.mullie.eu/parallel-processing-multi-tasking-php/) – user1978142 Jun 29 '14 at 03:53
  • 1
    actually what i used there in the tutorial was `popen()`, just spawn child processes, and the other one i used, redirection `> /dev/null &`, just to provide context, it was for AWS ses, it was a cli too, with cron – user1978142 Jun 29 '14 at 04:05
  • The only reason I don't want to use popen is because I distribute the cli tool as a phar file and running `popen('php some/file.php', 'r')` would look weird inside a phar, IMMO. – marcio Jun 29 '14 at 04:08
  • oh okay, anyways whatever should fit to what you need to do, i really cant put this as an answer since some situations are unique than others. – user1978142 Jun 29 '14 at 04:11

1 Answers1

0

Depending on how PHP is configured, it's generally attached to a single thread (1 thread per request because this is a web scripting language). So that means synchronous execution.

The only way I could think of doing something like this would be to load a page that does an AJAX call (where the other thread is asynchronous). I can't think of any way to do that in the original thread because, by definition, all threads are autistic (thread A doesn't know what thread B is doing, etc)

Machavity
  • 30,841
  • 27
  • 92
  • 100