Example Analysis of PHP file lock and Process lock

Source: Internet
Author: User
Tags flock
In view of the previous introduction of the Swoole, the Swoole server/client and the multi-process mechanism are used to describe the lock. This article mainly introduces the PHP file lock and Process lock Use example, here only for the PHP lock mechanism to explain, because the SQL lock and its function and application scenario is different, will be described separately. Hope to help everyone.

1. File lock

    • Flock ()

    • Fclose ()

    • Swoole_lock ()

The possible scenarios for file locks are:

1. Limit concurrent multi-process or multiple servers need to access and modify the same file;

2. The process of participating in file I/O is queued and artificially blocked;

3. Protect the contents of the file in the business logic;

The following is the use of File lock C/s communication mechanism, has omitted the specific communication process

Server (server communication process has been abbreviated):

Listen for data send event $serv->on (' Receive ', function ($serv, $FD, $from _id, $data) {  $serv->send ($FD, "serverend");  $p _file = "Locktest.txt";  Var_dump (file_get_contents ($p _file);});

CLIENT1 (server communication process has been slightly):

$s _recv = "ww"; $p _file = "Locktest.txt"; $o _file = fopen ($p _file, ' w+ ');//Flock () lock mode: Flock ($o _file,lock_ex);// Swoole lock mode://$lock = new Swoole_lock (Swoole_filelock, $p _file);//$lock->lock (); fwrite ($o _file, ' ss '. $s _recv); Sleep (30);//two ways to unlock//flock ($o _file, lock_un);//$lock->unlock ();

Client2 (server communication process has been slightly):

$s _recv = "xx"; $p _file = "Locktest.txt"; $o _file = fopen ($p _file, ' w+ ');//Flock () lock mode: Flock ($o _file,lock_ex);// Swoole lock mode://$lock = new Swoole_lock (Swoole_filelock, $p _file);//$lock->lock (); fwrite ($o _file, ' ss '. $s _recv);// Two kinds of unlocking mode//Flock ($o _file, lock_un);//$lock->unlock ();

Results:

The Client2 was blocked 30s until the Client1 execution was completed before the file was written once;

[L0.16@4 m29.5% C30s04] $ php swoole_client2.php

It is important to note that:

1. Both the flock () and the Swoole_lock () provided by Swoole have a mechanism to unlock automatically at the end of the process, so the demo will run normally even without manual unlocking, so the Sleep () is performed in the first client Pause function to observe the effect of file lock;

2.flock () Standard release method for Flock ($file, Lock_un), but personal like fclose (), Never trouble;

2. Process Lock

Unlike file locks, process locks are not used to block I/O to files, but rather to prevent unintended consequences caused by multi-process concurrency. Therefore, it needs to be queued during multi-process concurrency, that is, blocking the logical execution of other concurrent processes before the end of a process's critical logic execution.

There are several ways to achieve this:

1. Using the flock () file lock, create a temporary lock file, use the LOCK_NB to simulate blocking or non-blocking streams, and then use the decision conditions within the process to control the logic execution;

Non-blocking model demo:

$p _file = "Locktest.txt"; $o _file = fopen ($p _file, ' w+ ');//If the temporary file is locked, flock () will return Falseif (!flock ($o _file, LOCK_EX + LOCK_NB)) {  var_dump (' Process Locked ');} else {  //nonblocking model must add LOCK_NB parameter in flock ()///  of course, the cancellation of LOCK_NB parameter here is the blocking model  flock ($o _file, LOCK_EX + lock_nb);  Var_dump (' Process Locking ');  Simulates a long execution operation  Sleep (10);}

2. Using the shared memory provided by Swoole, the caching method or communication method passes a global variable in a different process, and the process obtains the state of the variable and uses the decision condition to control the logic execution;

There are many ways of passing variables, and here only one idea is given, taking memcached as an example;

Blocking Model Demo:

Initialize memcached$memcached = new Memcache; $memcached->connect ("localhost", 11211);//Gets the global variable used to make the state decision $s_flag = $ Memcached->get ("flag"), if (! $s _flag) {  //Here takes advantage of Memcached's expiration time as a demonstration, actually destroying the variable after business processing is complete  $memcached->set ("Flag", "locked", 0, ten);  Main ();} else {  //block model  while ($s _flag = = ' Locked ') {    var_dump (' Process locked, retrying ... ');    Set the retry time to avoid too frequent operation attempts    sleep (1);    Update the state variable    $s _flag = $memcached->get ("flag");  }  Non-blocking model  //if ($s _flag = = ' Locked ') {  //   var_dump (' Process locked, suspended ');  Die   ();  }  main ();} Analog business main function functions main () {  var_dump (' Process Running ');  Recovery of memcached  //$memcached->delete ("flag") after completion of business execution;

It is important to note that:

1.memcached expiration time must not be less than the actual time the program runs, it is recommended a little longer, after the logical execution of the recovery;

2. In a non-blocking model, if the status is determined to be false, the process should be aborted or block to avoid the continuation of the business logic;

3. In practical applications, it is necessary to set a retry time, which can greatly reduce the large amount of I/O concurrency for memcached and reduce the server pressure;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.