0

I have a php worker for gearman running from command line (through supervisord), that acts as a kind of "API". The worker uses mysqli connections to retrieve data from a DB and sends it back to a connected client.

class My_worker{
    private $worker;
    static $SQL;

public function __construct($SQL){

    $this->worker = new GearmanWorker();
    $this->worker->addServer();
    self::$SQL = $SQL;

//register workers
    $this->worker->addFunction("testA", array($this, 'testA') );
    $this->worker->addFunction("testB", array($this, 'testB') );
   }

public function run(){
    while ($this->worker->work()); 
}

static function testA(){ /* select field1 from DB; fetch row; return serialized; */}
static function testB(){ /* select field2 from DB; fetch row; return serialized; */}

}

//start worker
  $sql = new DB(SQL_HOST, SQL_USER, SQL_PWD, SQL_DB); //  Extends mysqli class
  $worker = new My_worker($sql);
  $worker->run();
}

So, I have e.g. two functions 'testA' and 'testB' that do certain selects from the db. The problem is that they share the same db connection, so if there are requests to both functions at the same moment, one could get results from "wrong" select i.e. testB fetches result from select that was called from testA and not testB.

Is there any way to avoid this, except by opening separate DB connections in each function?

user2531657
  • 339
  • 2
  • 9

1 Answers1

0

IMHO, Queries are always handled in parallel and there shouldn't be any issues with the current setup. I can imagine this improved by using PDO and transactions

Gundars Mēness
  • 488
  • 4
  • 17
  • No, they are not in parallel, because they share the same object to access the db, so e.g if I call db->select() in *testA*, I can still do db->fetch in *testB* even 5 minutes later. Of course, I can try to db->result->free() , but this does not solve the problem of parallel requests. One solution I have in my mind is to call GearmanWorker::unregisterAll, so that no other calls can be made to this worker while processing the data. – user2531657 Aug 08 '13 at 08:33
  • I think I found a solution. I've made results returned from db select local within each function. – user2531657 Aug 08 '13 at 08:55