开发者

How to block multiple users accessing single method at same time in PHP?

开发者 https://www.devze.com 2023-03-27 02:01 出处:网络
I am developing a record storage system which stores scanned, indexed and encrypted records in physical boxes.

I am developing a record storage system which stores scanned, indexed and encrypted records in physical boxes.

I have a method say "getAvailablePlace()" which checks what box and what seq is available for store. I want to lock this method. Ie when one user is entered into this method and he gets box:12 seq:55 as empty place..simultaneously at same time another user is accessing same method he may also get same val开发者_Python百科ues..box:12 seq:55 which is error prone.

So if I can lock this method when one user is already into this process?

I am using SQLite, wamp and codeigniter.


I have this code in use:

define('LOCK_FILE', "/path/to/your/lockfile-".$argv[1].".lock");
if( isLocked() ) die("ALREADY RUNNING !!!!\n" );

function isLocked()
{
    # If lock file exists, check if stale.  If exists and is not stale, return TRUE
    # Else, create lock file and return FALSE.

    if( file_exists( LOCK_FILE ) )
    {
        # check if it's stale
        $lockingPID = trim( file_get_contents( LOCK_FILE ) );

       # Get all active PIDs.
        $pids = explode( "\n", trim( `ps -e | awk '{print $1}'` ) );

        # If PID is still active, return true
        if( in_array( $lockingPID, $pids ) )  return true;

        # Lock-file is stale, so kill it.  Then move on to re-creating it.
        echo "Removing stale lock file.\n";
        unlink( LOCK_FILE );
    }

    file_put_contents( LOCK_FILE, getmypid() . "\n" );
    return false;
} 

You may alter it not to check the pid and just use the file as lock info.


Here a general approach: Have another table which stores the boxes that are "locked" at the moment. Then expand "getAvailablePlace()" to check for locked boxes before generating the next box id. After generating the box id, write it into the lock table. All three operations must take place in a database transaction.

Another solution would be to count up sequence numbers in the database for each box. If you do the operations "get biggest sequence for box y, add1 to it, write it back" in a transaction you should be fine.


You can't do that in PHP, as each user receives his own 'runtime'. But you could do it with some external methods, e.g. locks table in database. So your function check if some record exists in the table, skip/return false or whatsoever if it is and Run protected code if it is not.

Note that you'll have to implement double-checking for truly error-free code.

0

精彩评论

暂无评论...
验证码 换一张
取 消