3

Assume I have an array of items and each GET call make a change on this array (may be add/remove/shift)

Would that be "thread-safe"? I know that Node.js is a single-threaded, yet is there a possibility that two GET requests would be handled "simultaneously"?

2 Answers 2

5

As node is single-threaded only one piece of code is ever being executed at any time. A callback (such as the callback from a remote HTTP GET request) will be added to the end of the event loop's message queue. When there are no more functions on the stack, the program waits for a message to be added to the queue, and runs the message's function (in this case, the request callback function).

If you are making parallel requests to a remote server then you won't get the requests completed in the same order each time unless you run the requests in series. The callback functions will never run at the same time, however - only one function can ever be executed at once.

Sign up to request clarification or add additional context in comments.

Comments

3

It would be thread safe because all operation on arrays are blocking. The only operations in node.js that are not blocking are I/Os. Since you don't have any async operation, there is no problem with your situation. (Except if you need to do something like an access to a database or such ?)

2 Comments

But if I call a function which make multiple operations on an array, is there a possibility that Node.js would stop somewhere in the middle of the operation to serve another call?
@AlonAlon That would effectively be multi-threading, so no. Your request processing code will complete before another is started. It does not matter whether your function will take 1 millisecond with 2 lines of code or 1 minute with many more operations.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.