For example:
var i = 0;
while(true)
http.request('a url', callback_f);
function **callback_f**(){
**i++**;
}
In my simple imaginary example, some request might try to increase i's value in the same time, How can I write a code which is thread safe in NodeJS?
asked Mar 22, 2014 at 6:45
Ali Bahraminezhad
3264 silver badges15 bronze badges
-
stackoverflow.com/questions/5200821/…bvj– bvj2014年03月22日 06:47:44 +00:00Commented Mar 22, 2014 at 6:47
1 Answer 1
You do not have to worry about threads in Node.js. Node.js handles all calls within a single threaded environment.
answered Mar 22, 2014 at 6:47
Hakan Serce
11.3k3 gold badges31 silver badges49 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Ali Bahraminezhad
Sounds awesome! Then I don't need to write something like delegation(in .netframeowrk) in NodeJS?
Hakan Serce
I do not know .NET delegation, but in Node.js almost all IO functions are implemented asynchronously which allows the system to call the callbacks in a single threaded manner. This is one of the most powerful properties of Node.js actually.
thefourtheye
@HakanSerce Not almost all, all
Hakan Serce
@thefortheye There are actually several synchronous APIs in Node.js. Check this for instance, nodejs.org/docs/v0.3.1/api/fs.html#fs.readSync
thefourtheye
@HakanSerce What I meant is, there is no Node.js function which does only synchronous IO (it may have Sync counterparts)
Explore related questions
See similar questions with these tags.
lang-js