brasimon
brasimon

Reputation: 779

Gearman with PHP - threads in worker

I have a problem with Gearman and the worker for PHP. I want to run the same function at the same time. But now Gearman seems to make it a queue.

The output I'm searching for is:

$ ./daemon.php  
Starting daemon...
Received job: H:www-dev1:15 
Received job: H:www-dev1:16 
Finished
Finished

But the output of current code is:

$ ./daemon.php  
Starting daemon...
Received job: H:www-dev1:15 
Finished
Received job: H:www-dev1:16 
Finished

Is there possible to fork GearmanWorker using pcntl_fork()?

Client:

$client = new GearmanClient();
$client->addServer();

$args = array('test' => 'test1');
$args = serialize($args);

$client->doBackground('test', $args);
sleep(1);
$client->doBackground('test', $args);

echo "Done";

Worker:

#!/usr/bin/php
<?php

echo "Starting daemon..." . PHP_EOL;

$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction('test', 'testFunc');

while ($worker->work()) {
}

function testFunc($job) {

    echo "Received job: " . $job->handle() . PHP_EOL;
    sleep(10);
    echo "Finished" . PHP_EOL;  
}

Upvotes: 4

Views: 2355

Answers (2)

jeni
jeni

Reputation: 440

you can try worker clone function to create more workers

GearmanWorker::clone(void)

Upvotes: -1

KingCrunch
KingCrunch

Reputation: 131931

One worker can handle one job at one time. If you need to execute more than one job, you need to create more than one worker of course. in your case just execute the "Worker"-script multiple times and put them in the background. Or (as you mentioned yourself) create forks, but the first one is definetly easier ;)

Upvotes: 5

Related Questions