GIJOW GIJOW - 3 months ago 29
PHP Question

pthreads waiting thread function to finish before move on

First time using pthreads. I've created one class that extends Threads and calling it from another as usual.

here is my code:

<?php
class TestThread extends Thread
{
//
function __construct($parameters) {
$this->reverse = $parameters;
}

public function run() {
try {
sleep(20);
// Connecting to mysql database
$cn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
INSERT INTO DEVICE_SESSION_ADDRESS (X, Y, Z)
VALUES (1,2,3)
} catch (Exception $ex) {
//do stuffs
}
}
}
?>


And I call this function from a Rest api method:

function test ($response) {
require_once 'TestThread.php';
$rev = new TestThread($response);
$rev->start();
}


Using Postman to test the rest api, it waits 20 seconds before releasing the call.
The function works, it inserts on database.

What can I do to solve it and call my class TestThread asynchronously ?

Answer

Due to the fact pthreads works perfectly I am convinced the problem has one of these reasons:

  1. pthreads is not installed. Check phpinfo() for pthreads section.
  2. You call pthreads inside an Apache request. In this case pthreads is not working as expected. See this note: https://github.com/krakjoe/pthreads under SAPI Support. You can use pthreads only as CLI.

Make sure both points are solved and then it will work!