Skip to content
Advertisement

Running async function in php

is it possible to create some php class which can run functions asynchronously? Here is what I have done so far:

JavaScript

Here is how I want to call it:

JavaScript

Advertisement

Answer

Recent versions of pthreads support closures as members, making the code very simple:

JavaScript

However, this is horrible, it’s hard to imagine any function that is so hungry that it requires a thread of it’s own.

You have started down the right path with the thought that you should reuse the context and create a worker thread, pthreads has all of this built in.

More sensible code using built in classes looks more like:

JavaScript

But this still doesn’t deal with a return value. I’ll assume that you want to retrieve the result of calls made using the Pool, in that case the code looks more like:

JavaScript

As you can see, a call to Background::getResult will result in the calling context waiting until a result is available, this may or may not be desirable, but makes for a good example.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement