This article mainly introduces information about the communication between semaphores and shared memory in the basic knowledge of PHP process communication, if you have any need, you can refer to the next article, which mainly introduces the information about the communication between semaphores and shared memory in the basic knowledge of PHP process communication. if you have any need, you can refer
It is not determined who executes the tasks first. this depends on the process scheduling algorithm of the kernel, which is complicated. As a result, multiple processes may simultaneously access the shared memory at the same time, resulting in unexpected errors. The Semaphore name is puzzling, but it is easy to understand according to its original English meaning.
Semaphore English [sem %f %:( r)] vt. signal, flag;
Similar to the role of a commander.
Next we will look at the use of the next pseudo-code semaphore.
1. create a unique semaphore identifier
$ftok = ftok(__FILE__, 'a');
2. create a semaphore resource ID
$sem_resouce_id = sem_get($ftok);
3. receive semaphores
sem_acqure($sem_resource_id);
4. release semaphores
sem_release($sem_resource_id);
5. destroy semaphores
sem_remove($sem_resource_id);
An inelegant example makes it easy for us to understand the usage of this semaphore in our daily life. After understanding it, we can apply it to our programming field.
A company only has one bathroom. When someone goes to the bathroom, they need to get a lock (semaphore), indicating that the bathroom is in use. The code is as follows:
sem_acqure($sem_resource_id);
After completing the restroom, the employee needs to open the lock and release the lock (semaphore), indicating that the lock can be used by others now. The code is as follows:
sem_release($sem_resource_id);
With a simple lock, we can know whether the current restroom (shared memory) can be used. This example is not elegant but illustrates the problem. This blog is also a tasteful blog. it is really not easy .... The following is the sample code:
0) {foreach ($ child_list as $ key => $ pid) {$ status = pcntl_waitpid ($ pid, $ status ); if ($ status> 0 | $ status =-1) {unset ($ child_list [$ key]) ;}} sleep (1 );} $ count = shm_get_var ($ shm_id, cmd_key); echo "$ count ". PHP_EOL; // destroy semaphores sem_remove ($ signal); shm_remove ($ shm_id); shm_detach ($ shm_id );