Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are nodejs data-structures thread-safe by design?

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.

like image 891
gkns Avatar asked Sep 02 '25 05:09

gkns


2 Answers

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.

like image 67
Robert Harvey Avatar answered Sep 04 '25 19:09

Robert Harvey


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.

like image 26
adpalumbo Avatar answered Sep 04 '25 18:09

adpalumbo