Jesses Software Engineering Blog
Hacklang Async Processing
One of the frustrations in working with PHP is the synchronous, blocking, behaviour of the language. There are PHP extensions, such as pthreads that offer quasi PHP threading; however, that requires extra considerations such as server setups, locking, shared state, etc., and is often times omitted from development discussions due to overhead/learning curve of writing threaded programs.
Hacklang, Facebook’s language which works along side PHP, offers asynchronous functionality out of the box, although the website currently warns against using in a production environment. What’s different about Hack’s async functionality, is that the programmer is not creating and managing multiple threads, they are simply defining work to be completed in batch. Once those tasks are completed, the program continues executing. Hack’s async framework keeps track of all the asynchronous operations, making the learning curve of the batch processing much lower than that of thread management.
Hack Async Example
Instead of going through an in-depth write up of how Hack async works, I’ll just provide an example. Hack’s async documentation provides a good overview of the concepts, however the examples can be a bit confusing to follow and aren’t practical.
The following example uses PHP’s curl_multi to make batch curl requests to 21 different websites. There are two example scripts, sync.hh and async.hh, to demonstrate the difference between synchronous and asynchronous processing. The async approach is able to execute all the curl_multi requests in parallel, processing them as they finish, while the sync approach waits for each curl_multi batch to finish before proceeding onto the next one.
I got some helpful examples from Christian Stocker.