illustrate
1. Semaphore: It is an atomic operation provided by the system. A signal quantity can only be operated by one process at the same time.
A process gets a signal and must be released by the process.
2. Shared memory: It is a public memory area opened by the system in the memory and can be accessed by any process.
At the same time, multiple processes can access this area. In order to ensure data consistency, this memory area needs to be locked or signaled.
Example
echo "parent progress pid:{$parentPid}n"; $childList = array(); //Create shared memory, create semaphore, and define shared key $shm_id = ftok(__FILE__,'m'); $sem_id = ftok(__FILE__,'s'); $shareMemory = shm_attach($shm_id); $signal = sem_get($sem_id); const SHARE_KEY = 1; // producer function producer(){ global $shareMemory; global $signal; $pid = posix_getpid(); $repeatNum = 5; for ( $i = 1; $i <= $repeatNum; $i++) { //Acquire the semaphore sem_acquire($signal); if (shm_has_var($shareMemory,SHARE_KEY)){ // If there is a value, add one $count = shm_get_var($shareMemory,SHARE_KEY); $count++; shm_put_var($shareMemory,SHARE_KEY,$count); echo "({$pid}) count: {$count}n"; }else{ // No value, initialization shm_put_var($shareMemory,SHARE_KEY,0); echo "({$pid}) count: 0n"; } // Release after use sem_release($signal); $rand = rand(1,3); sleep($rand); } } function createProgress($callback){ $pid = pcntl_fork(); if ( $pid == -1) { //Creation failed exit("fork progress error!n"); } else if ($pid == 0) { // Subprocess execution program $pid = posix_getpid(); $callback(); exit("({$pid})child progress end!n"); }else{ //The parent process executes the program return $pid; } } // 3 writing processes for ($i = 0; $i < 3; $i ++ ) { $pid = createProgress('producer'); $childList[$pid] = 1; echo "create producer child progress: {$pid} n"; } // Wait for all child processes to end while(!empty($childList)){ $childPid = pcntl_wait($status); if ($childPid > 0){ unset($childList[$childPid]); } } // Release shared memory and semaphore shm_remove($shareMemory); sem_remove($signal); echo "({$parentPid})main progress end!n";
The above is an introduction to PHP semaphores and shared memory. I hope it will be helpful to everyone.