S
S
shell_execute2016-02-04 13:23:07
PHP
shell_execute, 2016-02-04 13:23:07

How to properly organize record locking?

Good afternoon! Suppose we have a table in the database with such a device:

int id
int user_id DEFAULT NULL

And we have a PHP server that takes the ID of the records from the table above and writes to the user_id the ID of the first user that sent the request, for example:
SELECT user_id FROM table WHERE id = ID что нам пришел от клиента
Если user_id == NULL
UPDATE table SET user_id = ID юзера что прислал запрос WHERE id = ID что нам пришел от клиента

Since the server is naturally multi-threaded, there is a possibility that 2 requests from two different clients can come with the same ID almost at the same time. And for both, the user_id == NULL test will be true, and hence 2 UPDATEs will be performed.
Actually interests, how it is possible to avoid a similar unfortunate situation?
There are ideas to use row-level locking on the ID that comes from the client as soon as the request comes in, but it's not clear how to implement it correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shell_execute, 2016-02-04
@shell_execute

Sergey "Why not add the user_id is NULL condition to the UPDATE?"
Here is the perfect answer :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question