Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Read in a node.js related web document that it is a single threaded server. So it confuses me whether all data structures by default be thread-safe in a node server!

I have multiple call-backs accessing a global object like this :

callback1{
global_var['key'] = val;
callback2{
globalv_var['key'] = val;

'key' may be same at times and may be different as well. Will the global_var be thread-safe ? callbacks, as intended gets called back as and when something is done, in no particular order.

The callbacks are still executed one after the other. There are no two callbacks operating on the global object at the same time. – CBIII Jul 30, 2013 at 5:15

Node.JS contains a "dispatcher." It accepts web requests and hands them off for asynchronous processing. That dispatcher is single threaded. But the dispatcher spins up a new thread for each task, and quickly hands off the task to the new thread, freeing the dispatcher's thread for servicing a new request.

To the extent that those task threads are kept separate (i.e. they don't modify each other's state), yes, they are threadsafe.

All of the javascript you write for your node.js applocation executes as if it were running in a single thread.

Any multithreading occurs behind the scenes, in the I/O code and in other native modules. So there's no need to worry about the thread safety of any application code, regardless.

So background threads invoke on the main thread before doing actual work. And two blocks of work can't run at the same time. Interesting. Similar to a desktop application waiting for user input. And that input kicking off actions in the UI thread. – TamusJRoyce Jan 18, 2018 at 18:56

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.