Recently used PHP to deal with about 7k of network data, the existing network situation, time-consuming usually a second, run the entire program about nearly two hours.
Because it is too long to run a data, so planning to implement parallel processing through multiple threads, we can achieve real multithreading through pthreads extensions, rather than the common fsockopen to "simulate". Pthreads's official website introduces here: http://pthreads.org/
Note that if you try to exchange data between arrays, you'll be disappointed because the PHP array itself is not thread-safe, and the right thing to do is to inherit the stackable class. A simple demo is shown below:
The code is as follows |
Copy Code |
<?php Class Storage extends Stackable { Public Function Run () {} } Class My extends Thread { Public function __construct ($storage) { $this->storage = $storage; } Public Function run () { $i = 0;//www.111cn.net while (+ + $i < 10) { $this->storage[]=rand (0,1000); } $this->synchronized (function ($thread) { $thread->notify (); }, $this); } } $storage = new Storage (); $my = new My ($storage); $my->start (); $my->synchronized (function ($thread) { $thread->wait (); }, $my); Var_dump ($storage); ?> |
In the example above, if $storage is an array, then the dump will be null.
When multithreading is enabled, the time to run the data can be compressed into 1000 seconds, less than 20 minutes, within the range of my acceptance
Finally found an auto load bug
The thread's Run method can inherit the main thread's constants, the function definition. Ini_set () and automatic loading cannot be inherited.
Specific what can inherit what cannot inherit not found the relevant documents, can only explore themselves.
Inherited functions can only do some basic operations, if you try to new an object (such as PDO) and then return the object will cause the process to terminate unexpectedly.
At present, it is basically not used in production environment.