In most php development, the lock mechanism is rarely used, but in some cases, locks are required for processing. For example, if the cache data is lost, many backend data requests are generated, the backend may be suspended, and the lock mechanism will be useful. Here we mainly introduce the Memory Lock Based on semaphore. Because there is no extension implementation in windows, we need to test it in Linux.
<? PHP $ key = ftok ('/tmp', 'A'); $ id = sem_get ($ key); If (sem_acquire ($ id) {echo "acquire ID, and sleep 5s \ n "; sleep (5); echo" 5 s past, release ID \ n "; sem_release ($ id );}
To execute this file on the command line, you must execute the file in two independent shell environments. Otherwise, the second execution will not begin until the first execution ends,
<? PHP $ key = ftok ('/tmp', 'A'); $ id = sem_get ($ key); $ k = 1; $ I = array ('K' => 0); If (sem_acquire ($ id) {$ shmid = shm_attach ($ key); If (shm_has_var ($ shmid, $ k) {$ I = shm_get_var ($ shmid, $ K); $ I ['K'] ++; shm_put_var ($ shmid, $ K, $ I );} else {shm_put_var ($ shmid, $ K, $ I);} sem_release ($ id );}
This sectionCodeThe implementation is to lock the shared memory, and then write the variable value to the locked memory. Writing the variable must support serialization.Type
There are two problems:
1,Sem_get returnsSemaphore ID, used for sem_acquire
2,Shm_attach returns the shared memory IDUsed by SHM _ * series Functions
From the test results, shell testing is used here and the results are displayed multiple times.
For I in 'seq 1 1000 '; do PHP test-sysvsem.php; done
<? PHP $ key = ftok ('/tmp', 'A'); $ id = sem_get ($ key); $ k = 1; $ I = 0; $ shmid = shm_attach ($ key); If (shm_has_var ($ shmid, $ k) {var_dump (shm_get_var ($ shmid, $ K ));} else {echo "Var $ K is not find ";}
No results are correct after tests
At last, I also said that FastCGI + PHP is usually used, and PHP of multi-threaded version is rarely used. I don't know the differences between multi-thread and multi-process PHP. If anyone knows what I want to tell