These days, for work reasons, a PHP-written background program needs to be re-serialized to parallel execution. This inevitably involves multi-threaded/multi-process related technologies. PHP seems to have no mature multi-threading mechanism, and a relatively mature process mechanism. Multi-process programming inevitably involves the IPC (inter-process communication). The IPC Technology of PHP is still quite many, can see in the PHP source code directory (Php_src/ext) Sysvshm,sysvsem,sysvmsg,shmop and other extensions, these can be used in the IPC, the following brief introduction:
PCNTL-Provides process-dependent operation functions Sysvsem-semaphores, all known as System V Semphore, can be used to limit the number of processes that access shared resources, typically set to 1, using SYSVSHM as a mutex-shared memory, full name of System V shared me Mory, is used to provide a shared memory mechanism, the feature is to eliminate the customer code serialization and deserialization of the trouble, variable-level access control, very easy to use, belonging to the novice using the way. SHMOP-Shared memory operation extension, unlike SYSVSHM, is the bit-level control that requires manual serialization and deserialization, but if used urgently, memory usage is higher than SYSVSHM, which is the master advanced method. SYSVMSG-Message Queuing, a special kind of shared memory, can be found here.
Here are the examples of using Sysvsem, as a memo, see the code for details, here are just a few key points to note:
The key of the Shm_attach and Sem_get methods need to be associated with the main process ID to avoid both components running at the same time, because shared memory and semaphores are system-level resources, and processes are common, and if not handled, can cause confusion between multiple instances. When the parent process waits for a child process, it consumes a lot of CPU, and can avoid the busy and so on by the way of sleep. The parent process waits for a child process to have a time-out mechanism, avoiding the need to wait for the child process logic to exit in the specified place, and not execute the code of the parent process, otherwise it will be confusing. The common way is to wrap the logic of the child process with a try catch, and after catching the exception, exit.
0) {echo "{$nPID} exit\n"; + + $n; } sleep (1); Avoid busy wait}//Clear Shm//shm_detach ($nShmID); Sem_remove ($nSemID); Shm_remove ($nShmID); echo "finished\n";? >
Related information
PHP ipc:http://blog.csdn.net/eroswang/article/details/2195260
PHP IPC System V and shmop:http://liangfen1224.blog.163.com/blog/static/72377647201111163317325/