[Solved] How to add pthreads to MAMP PRO PHP


This question was an XY problem and it didn’t deserve so many downvotes.

The real problem

how to perform a long running task while returning a response to the client so they don’t feel the app is slow

The solution

Using PHP-FPM and function fastcgi_finish_request

Example

<?php

// This is the output that we return to browser.
echo 'Your request has been accepted';

// "hang up" and send the data to the web server 
fastcgi_finish_request();

// Now perform the long running task (this gets executed in background, sort of)
$i = 1;

while($i--)
{
    // We're wasting some CPU cycles to simulate "work" (don't use this in real app)
    sleep(1);
}

Potential problems

Even though you can return a response to the client, a PHP-FPM child process will still be occupied until the task is completed. Since by default you don’t boot many of these processes, you can quickly run out of processing power.

Use with care

Alternative solution

Alternative would be to use a job queue based approach. A long running process (daemon written in PHP or something done with Node.js) reads a queue of tasks (from database / nosql, whichever you’re familiar with) and executes tasks.

Frontend-facing PHP simply fills the queue and notifies the client that job has been queued without actually doing the work.

That way you can have multiple workers performing long-running tasks by reading from same job queue source. Even if one dies or something else bad happens, you can always resume the work by restarting the worker process.

2

solved How to add pthreads to MAMP PRO PHP