Home >Backend Development >PHP Problem >How to implement blocking in php

How to implement blocking in php

coldplay.xixi
coldplay.xixiOriginal
2021-02-24 17:27:582789browse

php method to implement blocking: first open or create the file [lock.txt] in read-write mode; then apply [exclusive lock] to the [lock.txt] file; finally, after processing the data, [release lock] and fclose to close the open file.

How to implement blocking in php

The operating environment of this tutorial: Windows 7 system, PHP version 5.6, DELL G3 computer. This method is suitable for all brands of computers.

How to implement blocking in php:

1. First, open or create the file lock.txt file in read-write mode

2. Give lock. txt file. After the lock is successful, you can proceed to the next step of "processing the order product data"

3. After processing the data, you must "release the lock" and fclose the open file

Note: After giving the file an "exclusive lock", if there is no "release lock" inside, there will be a very stuck situation

public function index(){
    $fp = fopen("lock.txt", "w+");
    if(flock($fp,LOCK_EX))
    {
        $find=Db::name('user')->where('username','name2')->find();
        if($find){
            $data['username']='name3';
            $data['password']='';
            $data['password_m']='';
            Db::name('user')->insert($data);
        }else{
            $data['username']='name2';
            $data['password']='';
            $data['password_m']='';
            Db::name('user')->insert($data);
        }
        flock($fp,LOCK_UN);
    }
    fclose($fp);
    return 'success';
}

Note: It is feasible for small concurrency, and the performance will not improve Big impact. It is better if the concurrency is less than 500. If it is too high, it is recommended to use queue mode.

Related free learning recommendations: php programming(Video)

The above is the detailed content of How to implement blocking in php. 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