S
S
Schrödinger's cat2016-03-13 18:16:34
Node.js
Schrödinger's cat, 2016-03-13 18:16:34

Is a race condition possible and how to avoid it?

Hello, I'm new to node.js, before that I wrote web application code in php. Actually, as far as I know, the code in node.js is executed asynchronously and I had the following question:
For example, there is a page with seats in the cinema hall, or with available seats on the plane, the user can randomly select an unoccupied seat, or press the button to select "randomly".
The server has a chain of handlers, but in the case of the "random" option, an intermediate handler is added that looks at the occupied places in the database and, based on the data received, selects the unoccupied one and passes it further along the chain.
If user #1 presses the select button randomly, and user #2 chooses a random seat AFTER user #1 (for example, number 10) and user #1 randomly gets seat 10, is there a chance that user #2 will take a seat faster than #1 ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Shemsedinov, 2016-03-13
@MarcusAurelius

It depends on where the data on occupied places is stored on the server and how the booking is made. For example, if there is a table of places in the database, and in order to occupy the next random one from the node, two queries must be made:
1) Select a random one
2) Mark the selected one as busy
Then a request from another user can squeeze in between these requests and ruin everything. But if this operation is atomic, i.e. is sent to the DBMS and 1 and 2 together and the number of a random place is returned, then everything will be ok. But the best thing in this situation is to immediately take all the places in memory into an array, randomly mix them there once. arr.sort(function () { return Math.random() - 0.5; }); and then take on demand one arr.pop(); and if the server is in the same stream, then this guarantees that no one will take the same one. But you can save to the database already in the pending mode. If the request flow is very large, then it’s more difficult, you can’t do it with one thread, you need to divide the array into blocks and keep each block in a separate process or a separate server.

S
Super User, 2016-03-13
@sergeystepanov1988

If user #1 clicks on the "Randomly Select" button and his request is still being processed, he won't get any seats yet. If at this time user #2 presses the same button and his request goes faster and he gets 10, then #1 should not get the same number when his request is done.
In general, you can talk about spherical users in a vacuum pressing spherical buttons for a long time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question