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!
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; } } }
Related recommendations:
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!