0

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?

  • http://stackoverflow.com/questions/5200821/grasping-the-node-js-alternative-to-multithreading – bvj Mar 22 '14 at 06:47

1 Answers1

1

You do not have to worry about threads in Node.js. Node.js handles all calls within a single threaded environment.

Hakan Serce
  • 11,198
  • 3
  • 29
  • 48
  • 1
    Sounds awesome! Then I don't need to write something like delegation(in .netframeowrk) in NodeJS? – Ali Bahraminezhad Mar 22 '14 at 06:50
  • 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. – Hakan Serce Mar 22 '14 at 06:58
  • @HakanSerce Not *almost all*, all – thefourtheye Mar 22 '14 at 06:59
  • @thefortheye There are actually several synchronous APIs in Node.js. Check this for instance, http://nodejs.org/docs/v0.3.1/api/fs.html#fs.readSync – Hakan Serce Mar 22 '14 at 07:02
  • @HakanSerce What I meant is, there is *no* Node.js function which does only synchronous IO (it may have Sync counterparts) – thefourtheye Mar 22 '14 at 07:14