D
D
Dorothy2017-01-22 21:04:13
MySQL
Dorothy, 2017-01-22 21:04:13

How to avoid concurrent access to the same record?

Hello.
There is a table with records that will be assigned to different users. By default, entries are not associated with any user.
Table view

id | user_id | data
1 | 0 | 123
2 | 0 | 456
3 | 0 | 798

The next free entry in this table must be assigned to the user by changing the user_id and get this changed entry.
I see the algorithm of work as follows: select one free entry and change its user_id.
The problem is as follows, it is possible that there will be several simultaneous requests for a free record. For example, two requests were initiated to assign a free record to a user through requests to the web server. A free record was selected, for example, with id 1. The second request also selected a record with id 1, since it is still free. The first request assigned the user_id value it wanted, and the second request did the same.
As a result, the record is assigned to the user from the second request, and the user from the first one is left with nothing.
How is this situation resolved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2017-01-22
@Dorothy

SELECT FOR UPDATE
https://www.laravel.com/docs/5.3/queries#pessimist...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question