Tom Tom - 1 year ago 210
PHP Question

How to add pthreads to MAMP PRO PHP

How to add pthreads to MAMP PRO PHP 5.6.10 on MAC OS X 10.11?

How to install it and recompile PHP to use --enable-maintainer-zts ?

Answer Source

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



// 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 

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

    // We're wasting some CPU cycles to simulate "work" (don't use this in real app)

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.