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.
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.
Share Improve this question asked Jul 30, 2013 at 5:13 gknsgkns 7302 gold badges15 silver badges35 bronze badges 2- 2 The callbacks are still executed one after the other. There are no two callbacks operating on the global object at the same time. – CBIII Commented Jul 30, 2013 at 5:15
- 3 possibly related: stackoverflow./questions/7018093/… – Paul Commented Jul 30, 2013 at 5:18
2 Answers
Reset to default 4Node.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.