0

I have a table named and spot and reservation. spot contains column spot_id and spot_status. For reservation process i start a transaction and then acquire lock on specific row using this query. I am using php and mysql.

//start transaction

SELECT * FROM spot WHERE spot_id = $id FOR UPDATE ;  
//if this query is successful then   

1. set spot status to 1
2. insert corresponding values in reservation table.  

and then commit else rollback           

//transactions ends

lets say there are 2 concurrent transactions T1 and T2 which tries to reserve the same spot. From what i learnt from other's questions and answers in this site, if the transactions are not concurrent there would not be any problem, but in concurrent operation the processor can change from schedules of T1 to T2 anytime . After acquiring the locks on row by T1, lets say processor switch to transaction T2. T2 then tries to acquire locks on that same row but it cannot as it is locked by T1.

my questions are theoritical :

  1. When is the lock removed by mysql? or is there any explicit way of removing lock myself?
  2. Since T2 transaction cannot lock the row which is the first query , does it rollback? or does processor keeps T2 waiting until it can lock the row?
  3. what is the possibility of deadlock occuring in this problem?

2 Answers 2

0

Your strategy for lock management is correct.

If T1 first obtains the lock on spot/spot_id=$id, then T2 will wait until T1 either commits or rolls back the transaction. If T1 crashes or times out the rollback will be implicit.

If you want a deadlock, try this.

Get T1 to lock row 1 ("fork") and then row 2 ("knife"). Get T2 to lock row 2 ("knife") and then row 1 ("fork").

Run them concurrently. Eventually you'll get T2 holding only a knife, and T1 holding only a fork. They'll be staring at each other, going hungry, each waiting for the other to set down an implement.

0

Lock is removed when transaction which obtained the lock is ended that is committed or rolled back. There is no way in mysql to release row level lock until end of transaction because:

InnoDB stores row locks in a format such that it cannot know afterward which lock was set by which statement

However you can use user defined locks (aka advisory locks aka cooperative locks) which can be released at any moment.

T2 transaction will wait till lock can be acquired but no more than inno_lock_wait_timeout seconds. In the later case error will happen that lock cannot be acquired.

If you lock the row by id and then modify only this row then deadlock cannot happen. For deadlock to happen you need at least two resources which are acquired by transactions in different order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.