Im using PHP-FPM to run a Phalcon application and have just installed pthreads so I can start running tasks asynchronously. I currently have pthreads working using the command line interface:
<?php
/**
* Author: Abu Ashraf Masnun
* URL: http://masnun.me
*/
class WorkerThreads extends Thread
{
private $workerId;
public function __construct($id)
{
$this->workerId = $id;
}
public function run()
{
usleep(2000000); // 2 seconds
echo "Worker {$this->workerId} ran" . PHP_EOL;
}
}
// Worker pool
$workers = [];
// Initialize and start the threads
foreach (range(0, 5) as $i) {
$workers[$i] = new WorkerThreads($i);
$workers[$i]->start();
}
// Let the threads come back
foreach (range(0, 5) as $i) {
$workers[$i]->join();
}
die('finished');
^^ all of that works running php test.php
from the shell.
But I am unable to get this example to work using the fast process manager. I have a controller initializing a thread object and calling start()
, but none of the logic in the run()
method executes as it should.
Controller:
<?php
public function indexAction()
{
$threads=[];
for ( $i = 0; $i < 2; $i++ )
{
$threads[$i] = new AsyncThread();
$a = $threads[$i]->start();
$b = $threads[$i]->isStarted();
Phalcon\DI::getDefault()->get('logger')->log(json_encode($a));
Phalcon\DI::getDefault()->get('logger')->log(json_encode($b));
}
for ( $i = 0; $i < 2; $i++ )
{
$threads[$i]->join();
}
die('done');
AsyncThread.php:
<?php
class AsyncThread extends Thread
{
public function __construct()
{
Phalcon\DI::getDefault()->get('logger')->log( 'construct' );
}
public function run()
{
usleep(2000000); // 2 seconds
Phalcon\DI::getDefault()->get('logger')->log( 'running' );
}
}
When this runs my logs show:
[Tue, 17 Nov 15 22:10:43 +0000][INFO][][] construct
[Tue, 17 Nov 15 22:10:43 +0000][INFO][][] true
[Tue, 17 Nov 15 22:10:43 +0000][INFO][][] true
[Tue, 17 Nov 15 22:10:43 +0000][INFO][][] construct
[Tue, 17 Nov 15 22:10:43 +0000][INFO][][] true
[Tue, 17 Nov 15 22:10:43 +0000][INFO][][] true
I expect to see 'running' log asynchronously, but it never logs at all.
My goal is to just get a hello world example of posix threads working with PHP-FPM so I can begin building a well thought out solution for my needs.