0

I have code structure like this

 echo "First Operation"; sleep(3); echo "Second Operation"; 

I want to try simulate multi-threading but I could not make, sleep function is meaningless there, but I could not find another option.

6
  • 1
    How do you "simulate" multi-threading? PHP has no multithreading except with MPM worker for Apache. Commented Jul 16, 2013 at 14:49
  • I know it, that's why I'm 'trying' :D Commented Jul 16, 2013 at 14:50
  • 2
    But...what are you really trying to do? PHP will just work it's way from the top of the script downwards. There's no way to change that. How do you simulate something that you can't change like that? Commented Jul 16, 2013 at 14:52
  • stackoverflow.com/questions/12394027/…, perhaps u'll find some pointers there Commented Jul 16, 2013 at 14:54
  • You can do forking (which is similar to multithreading) as long as you're on the CLI. php.net/manual/en/function.pcntl-fork.php Commented Jul 16, 2013 at 16:01

1 Answer 1

1

I have to agree that PHP is not built for multithread. As such the script you create will always run in one thread. There are some exceptions to that. When you call a shell command there is the possibility to fire-and-forget the command when you dont need the output. It runs parallel but you can not access the result.

PHP is designed to execute one instruction after the other.

To create something like a parallel working script, you need to take advantage of some external systems. All of those tricks are related to your actual solution you wane try to accomplish. Let me give you an example.

You could use a Message Queueing system like Rabbit MQ to work as a separation between one script and the other. Lets say script1 is permanently listening on the queue for work to do. Another script, lets say script2, is (on request) bushing a work into the queue and continuing with other stuff while the script1 is picking that up, doing something and returning the answer. When script2 is done with the other stuff it can read the result from the queu and finish whatever you want to do.

This is actually a very tricky and theoretical concept, but it might give you an idea. But without any external component like the queue, php will not work multithreaded.

I hope that is helping you!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.