0

Please note, I am not looking to use curl_multi for this solution.

Basically, I'm wondering how I can use CURL in pThreads while sharing a connection instance. For example, the following code (based on https://stackoverflow.com/a/42880619/7655670) works fine:

class SearchWorker extends Worker {
    public function run() {}
}

class Search extends Thread {
    public $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function run()
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, 'http://httpbin.org/get?search='.$this->data->s);
        $this->data->r = curl_exec($ch);
        curl_close($ch);
    }
}

$pool = new Pool(4, 'SearchWorker');
$data = [];
$search = array('cats','dogs','cows','cars','trucks','booze','bottles','furniture','metal','elements');

foreach ($search as $i => $s) {
    $dataN = new Threaded();
    $dataN->i = $i;
    $dataN->s = $s;
    $data[] = $dataN;
    $pool->submit(new Search($dataN));
}

while ($pool->collect());

$pool->shutdown();

However, next I tried moving the CURL instance to the Pool Worker threads so that they could be shared by the threads being executed under them. However, this code crashes (after returning the correct results):

class SearchWorker extends Worker {
    private $ch;

    public function __construct()
    {
        $this->ch = curl_init();
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE);
    }

    public function run() {}
}

class Search extends Thread {
    public $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function run()
    {
        curl_setopt($this->worker->ch, CURLOPT_URL, 'http://httpbin.org/get?search='.$this->data->s);
        $output = curl_exec($this->worker->ch);
        $this->data->r = $output;
    }
}

Result:
https://i.stack.imgur.com/5LktH.png

Am I missing something? Can I modify this code to work without crashing or is there something more fundamental that prevents this from working properly?

Thanks!

Community
  • 1
  • 1
MJC
  • 57
  • 9
  • The fundamental problem is resources are unsupported. The extension author has written about it multiple times, e.g. http://stackoverflow.com/a/20973134/3942918, https://github.com/krakjoe/pthreads/blob/70040812d22798c3dd4cfc3b612bd9f56a1dc7ba/examples/SocketServer.php#L2-L14, https://github.com/krakjoe/pthreads/issues/664#issuecomment-274348966 – user3942918 Mar 30 '17 at 13:00
  • Not sure how that didn't come up in my searches... answers my question though, thanks – MJC Mar 30 '17 at 13:40

0 Answers0