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!