1

i wanted perform curl reuse in thread like here : PHP Curl Reuse Optimization
but when i executed this code :

//main code
$n=0;
$app = [];

$app_default = new WebRequest();

for ($n = 0; $n < 50; $n++){

    $app[$n] = $app_default;
    $app[$n] -> start();

}
//
//base thread class
class WebRequest extends Thread {


    public function run() {
        $this->executeREUSEGET();
    }

        private $ch = null;

        function executeREUSEGET()
        {
            if ($this->ch == null) {
                $this->ch = curl_init();
                curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "GET");
                curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
                curl_setopt($this->ch, CURLOPT_ENCODING, '');
            }
            curl_setopt($this->ch, CURLOPT_URL, 'https://www.google.com/');

            /* Result handling and processing */
            $result = curl_exec($this->ch);
            return $result;
        }
    
}

get these errorrs :

PHP Fatal error:  Uncaught RuntimeException: the creator of WebRequest already started it in D:\req.php:71

how can i solve this?

i dont want to execute curl_unit() & curl_setopt() in every request in loop.bcz it gets slow down...
actually i wanna send curl request in a while loop in pthread and bcz speed is so important for me i dont need to initialize curl in every request(url and curl_setopt are static).it reduce speed.

Florian Weimer
  • 32,022
  • 3
  • 48
  • 92
ehsan
  • 29
  • 1
  • 6

1 Answers1

1

i found this code but work only one time.it means only get site contents for once :((

$appa = new Atomic();
$ok = $appa -> inc();
//
$n=0;
$app = [];
//
for ($n = 0; $n < 50; $n++){

    $app[$n] = new WebRequest($ok);
    $app[$n] -> start();

}
///
class WebRequest extends Thread {
    
    public $ch;

    public function __construct($ch) {
        $this->ch = $ch;
    }
    
    public function run() {
            $result = curl_exec($this->ch);
            echo $result;
    }

}
///
class Atomic extends Threaded {

    public function inc() {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
            curl_setopt($ch, CURLOPT_ENCODING, '');
            curl_setopt($ch, CURLOPT_URL, 'http://www.example.com');
            return $ch;
    }

    
}
ehsan
  • 29
  • 1
  • 6