Co-operative PHP Multitasking

When is an array like an adventure?

Christopher Pitt
Async PHP
11 min readMar 28, 2015

--

Last week I got the opportunity to share recent work with my colleagues, at SilverStripe. I was going to present Async PHP today, but since I covered ReactPHP last week; I decided to talk about something slightly different. So here’s a post about cooperative multitasking.

I’m also planning on adding this stuff to the Async PHP book I’m writing. It’s going to include far more detail than you’ll read in this post, but I still think this post is a good overview of the topic!

Let’s go!

That’s the point of everything we’re going to look at. But we’re going to start somewhere simpler and more familiar.

It All Starts With Arrays

We can use arrays for simple iteration:

This is the kind of basic functionality that our daily code depends on. That is; being able to traverse an array and determine the keys and values of each item.

Naturally, we would want to be able to know when we’re working with an array. There’s a handy built-in function for just this purpose:

Array-like Stuff

There are times when we get hold of things that act in this way, but are not arrays. Consider working with the DOMDocument class:

This clearly isn’t an array, but it has a length property. Can we traverse this, in the same way we can traverse arrays? We can find out by checking whether it implements a special interface:

That’s really helpful. We don’t have to trigger errors if the thing we want to traverse isn’t traversable. We can just check beforehand.

That leads to another question: could we make our own classes that behave in the same way? The answer is yes! Our first approach might resemble the following:

If we run that, we’ll see an error message:

PHP Fatal error: Class MyTraversable must implement interface Traversable as part of either Iterator or IteratorAggregate…

Iterator

So we can’t directly implement Traversable, but we can try one of the other two…

This interface requires that we implement 5 methods. Let’s expand on our iterator:

Some important things to notice:

  1. We’re storing the constructor $data array so we can return items from it later.
  2. We also need an internal index (or pointer) to track things like current and next.
  3. rewind() just resets the index so that current() and next() will work as expected.
  4. Keys don’t have to be numeric! That’s just what I’m using here, to keep things simple.

We can run this code with:

So this seems like a lot of work, but it’s a neat way to hook into the foreach/for functionality that arrays have.

IteratorAggregate

Remember the second interface that Traversable exception suggested we implement? Turns out it’s a lot quicker to implement than Iterator:

We’re cheating a bit. Instead of implementing a whole new Iterator, we’re decorating ArrayIterator. Still, this is much less code than implementing a whole new Iterator.

Hold your horses! Let’s compare some code. First we’ll read each line in a file without a generator and then with:

This reads itself, and for each line it prints the line number followed by a line of code. So let’s make it a generator, because WHY NOT!

Now I know this looks more complicated. It is, but mostly because we’re not using file_get_contents(). A generator looks like a function, but it stops every time it gets to the yield keyword.

Generators look a little bit like iterators:

So it’s not an iterator, it’s a Generator. What methods does it have?

If you read a huge file, and use memory_get_peak_usage(), you’ll notice that the generator code uses a fixed amount of memory, no matter how big the file is. It’s only reading a single line at a time. Reading the whole file, with file_get_contents() uses more memory the bigger the file gets. This is one of the benefits of using iterators for this kind of thing!

Send

It’s possible to send data into a generator. Consider the following generator:

Notice how we’re wrapping the generator function within call_user_func()? That’s just a shortcut for defining the function and then immediately calling it to get a new generator instance…

We’ve already seen this kind of yield usage. We can extend this generator to accept data as well:

Data enters and leaves through the yield keyword. To begin with, current() executes the code until it sees yield, and returns foo. send() pushes it past that yield to where the generator prints the input. This takes some getting used to…

Throw

Since we’re jumping in and out of these functions, we might want to push exceptions into generators. That way they can handle the fallout in their own way.

Consider the following:

Now, let’s wrap this in another function:

So here we have a normal closure, wrapping the multiply generator. Let’s protect against invalid arguments:

What if we want the generator to be able to handle the exception? We can send it through to the generator!

That’s pretty neat! So: we can use generators just like iterators. And we can also send data into them and throw exceptions through them. They’re interruptible and resumable functions. Some languages would call these kinds of functions…

Turns out we can use coroutines to model asynchronous code. Let’s make a simple task scheduler. First we’ll need a Task class:

Task is a decorator for ordinary generators. We store the generator for later use, and implement simple run() and finished() methods. run() makes the task tick, while finished() lets the scheduler know when to stop running the task.

Then we need a Scheduler class:

Scheduler maintains a queue of running tasks. run() will run until the queue is empty, and pulls a task off the queue to run it. If the task is unfinished, after we run it once, we send it back to the queue.

SplQueue is great for this case. It’s a first-in-first-out structure, which ensures each task will get a fair amount of processor time.

We can run this code, with:

The first time we run this, we should see output resembling:

This is almost exactly what we want to happen. The trouble is the first runs of each task appear to happen twice. We can fix this with a small change to Task:

We need to adjust the first invocation of run() so that it reads the current generator valid. Subsequent invocations can advance the generator pointer…

Some folks have built wonderful libraries on this idea. We’ll just look at two, for now…

RecoilPHP

RecoilPHP is a set of coroutine-based libraries, the most impressive of which is a kernel for ReactPHP. It’s possible to swap the event loop from ReactPHP with the one from RecoilPHP, without major changes to your application.

Let’s look at some ReactPHP-only, asynchronous DNS resolution:

resolve() accepts a domain name and DNS resolver, and performs a standard ReactPHP DNS lookup. Don’t get too caught up in the internals of resolve(). The important thing is that the function isn’t a generator. It’s just a function!

run() creates a ReactPHP event loop, a DNS resolver (by way of a factory) and resolves a few domain names. Again, not a generator.

Wonder what the RecoilPHP differences are? Wonder no more!

It’s doing a few magical things to allow such tight integration with ReactPHP. Each time resolve() runs, RecoilPHP manages the promise, returned from $resolver->resolve(), and sends the data back into the generator. At that point we can use it as though we were writing synchronous code. Just a list of instructions, unlike the callback code we might be accustomed to in other asynchronous models.

RecoilPHP knows it should manage the array of yields, we return in run(), in this way. RecoilPHP also includes coroutine-based database (PDO) and logger libraries.

IcicleIO

IcicleIO is a new attempt to achieve the goals of ReactPHP, using only coroutines. It has fewer secondary libraries than ReactPHP. Still, the core asynchronous stream/server/socket/loop features are there.

Let’s look at an example socket server:

As far as I can tell, this code is doing the following things:

  1. Creating a server instance, at host 127.0.0.1 and port 6000, and passing that to the outer generator.
  2. The outer generator runs, while the server is open to new connections. When the server accepts a connection it passes it into the inner generator.
  3. The inner generator writes a welcome message to the socket. It then runs while the socket is readable.
  4. Each time the socket sends a message to the server, the inner generator checks if the message is exit. If so, the other sockets are informed. If not, the other sockets are sent the same message.

Open up terminal and type nc localhost 6000 to see this in action!

The example uses SplObjectStorage to keep track of the socket connections. This is so that we can send messages to all the sockets.

This topic can be a lot to take in. Hopefully you see where generators came from, and how they can help with iteration and asynchronous code.

If you’ve got questions, feel free to ask me.

I would like to thank Nikita Popov (especially for his illuminating post on co-opertive multitasking), Anthony Ferrara and Joe Watkins. The work of these gifted developers and teachers inspired me to write this post. Give them a follow, will ya?!

--

--