Justin Justin - 1 year ago 53
Node.js Question

Locking on an object?

I'm very new to Node.js and I'm sure there's an easy answer to this, I just can't find it :(

I'm using the filesystem to hold 'packages' (folders with a status extensions 'mypackage.idle') Users can perform actions on these which would cause the status to go to something like 'qa', or 'deploying' etc... If the server is accepting lots of requests and multiple requests come in for the same package how would I check the status and then perform an action, which would change the status, guaranteeing that another request didn't alter it before/during the action took place?

so in c# something like this

lock (someLock) { checkStatus(); performAction(); }

Thanks :)

Answer Source

There are no locks in node.js -- because you shouldn't need them. There's only one thread (the event loop) and your code is never interrupted unless you perform an asynchronous action like I/O. Hence your code should never block. You can't do any parallel code execution.

That said, your code could look something like this:

qa_action_performed = false
function handle_request() {
  if (check_status() == STATUS_QA && !qa_action_performed) {
    qa_action_performed = true

Between check_status() and perform_action() no other thread can interrupt because there is no I/O. As soon as you enter the if clause and set qa_action_performed = true, no other code will enter the if block and hence perform_action() is never executed twice, even if perform_action() takes time performing I/O.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download