Home  >  Article  >  PHP Framework  >  Introducing the use and examples of thinkphp lock

Introducing the use and examples of thinkphp lock

藏色散人
藏色散人forward
2021-05-12 17:15:334485browse

The following tutorial column will introduce you to the use and examples of thinkphp lock in the thinkphp tutorial column. I hope it will be helpful to friends in need!

Introducing the use and examples of thinkphp lock

##In development requirements, you will encounter such a situation, concurrent requests . Before the database update is completed, the data found by another select will be the data before the update, which will cause inaccurate query data.

How to solve it? This problem can be solved using innoDB transactions and locks. Before the update of our current row is completed, the data in the select query for this row will be locked.

For example, our database has two rows of data like this


Introducing the use and examples of thinkphp lock We update the num data with id=1 to 1000 and sleep for 10 seconds. At this time, when we select the data with id=1, it will Wait for the update to end. If we select id=2, we do not need to wait for 10 seconds, and the data will be obtained immediately.
This is InnoDB's row lock. It will only lock the row of data currently updated and will not lock the entire table.

The test code will be listed below. Remember to change the engine to innoDB, not MYISAM.

class Index extends Controller
{
    public function index()
    {

        $model=Db::name('test');
        $model->startTrans();
        try{
            $list=$model->lock(true)->find();
            $model->where(['id'=>1])->data(['num'=>900])->update();//id为1的更新
            sleep(10);//等待10秒
            $model->commit();
            print_r($list);
        }catch (\Exception $exception){
            $model->rollback();
            throw $exception;

        }




    }


    public function index2(){

        $model=Db::name('test');
        $model->startTrans();
        try{
            $list=$model->lock(true)->where(['id'=>1])->find();//id为1在更新时,select id=1 会等待。把ID改为2时,不等待
            $model->commit();
            print_r($list);
        }catch (\Exception $exception){
            $model->rollback();
            throw $exception;

        }

    }
}

Test steps: After requesting index, when requesting index2, you will see that index2 will wait for index loading to complete before we can see the print result of index2. If the id of index2 is changed to 2, it will not be affected by index.

Related recommendations:

The latest 10 thinkphp video tutorials

The above is the detailed content of Introducing the use and examples of thinkphp lock. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete