Recently in the study of PHP pthreads, I put the relevant learning notes organized under the share to everyone.
1. Enable multiple threads to execute concurrently.
1 <? PHP 2 class HelloWorld extends Thread {3 public function __construct ($world) {4 $this->world = $w Orld } 6 7 public function Run () {8 Print_r (sprintf ("Hello%s\n", $this-world)); 9 Sleep (1}12 for ($i =0; $i <10; $i + +) {$pool [] = new HelloWorld (' World ') $i}16 + foreach ($pool as $work) {$work-start ();
2. It is not possible to exchange data directly between threads because the PHP array itself is not thread-safe. Can be implemented by inheriting the stackable class. The specific code is as follows:
<?PHPclassHelloWorldextendsthread{Private $_data; Public function__construct ($data) { $this->_data =$data; } Public functionrun () {$this->_data[] = Thread::GetCurrentThreadID (); Sleep(1); } }classStorageextendsstackable{ Public functionrun () {}}$storage=NewStorage (); for($i= 0;$i<10;$i++) { $pool[] =NewHelloWorld ($storage);}foreach($pool as $work) { $work-start ();}Print_r($storage);
Write in the last few points:
1. Generally, the main thread is used to control each sub-thread.
PHP Pthreads Learning Notes