Home  >  Article  >  Backend Development  >  PHP implements lock and unlock principle

PHP implements lock and unlock principle

小云云
小云云Original
2018-03-10 10:24:553011browse

PHP does not have perfect thread support, and even deployment to an httpd server based on the thread model will cause some problems. However, even with PHP under the multi-process model, it is inevitable that multiple processes will access the same resource together. For example, a data cache shared by the entire program, or a specific process must be queued due to resource constraints, and a unique identifier is generated for each user. The PHP language itself does not provide process mutual exclusion and locking mechanisms, which makes programming in these situations difficult. Currently, the available options are as follows:

  • Use MySQL Locking mechanism to achieve mutual exclusion. The disadvantage is that it increases the connection burden on the database server and makes the program dependent on the database service to work properly.

  • Use the file locking mechanism. That is to say, the flock function is used to implement locking and mutual exclusion mechanisms through files to simulate the working mode of locking primitives under the general programming model. This method became a necessary element to protect data integrity in the past when plain text files were used as storage engines. Now it is also quite common when text files are used as caching media. PmWiki probably also uses this mechanism to remind multiple people when they edit a page at the same time. However, the file lock mechanism will somewhat call the file lock feature on the host operating system, so when using it, you must check whether the server operating system provides a complete and reliable file lock mechanism for the PHP environment.

  • Use shared memory space counting. PHP can use the shmop_open function to open up a memory space and share data between service processes. In order to ensure mutually exclusive and safe access to shared data, you can use the sem_get, sem_acquire and sem_release functions to implement the share count locking mechanism. This method is actually implemented in the background by calling the system's ipc service.

Related recommendations:

PHP’s method of locking and unlocking files

PHP adds Lock realizes the concurrent snap-up function

PHP uses flock to realize the function of locking files

The above is the detailed content of PHP implements lock and unlock principle. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn