Domanda

The API returns the following from several different sources:

{
  data: {'...'},
  version: 56
}

The idea is to only keep the most recent version:

// Our local state
var localDocument = {
  data: null,
  version: -1
};

var updateIfCurrent(document) {
  if (document.version > localDocument.version) {
    localDocument = document;
  }
}

$http.get('/foo', updateIfCurrent);
$http.get('/bar', updateIfCurrent);

So if any HTTP call returns an outdated version of the document, we don't replace our more current state.

However, lets imagine that localDocument.version = 1. Two updateIfCurrent calls come in with C1: document.version = 2 and C2 document.version = 3. Is it possible that they both pass the localDocument.version > document.version, and C2 finishes first and then C1 finishes resulting in document.version = 2 and not document.version = 3, as intended?

If yes, how to fix this?

È stato utile?

Soluzione

Is it possible that they both pass the localDocument.version > document.version...?

No, I don't see how that would be possible. JavaScript can only run one function at a time. Any "race condition" in JavaScript deals with which function gets to run first. All synchronous function execution is atomic, so whichever function runs first will completely finish before the next one begins.

Therefore, you are guaranteed that your second check for localDocument.version > document.version runs only after first function has completely finished.

Could this vary by JS engine implementation or is this guaranteed across different implementations?

Technically speaking, no language specification requires JavaScript to be single-threaded. Practically speaking, there does not exist any multithreaded JavaScript engine (except for engines that support sandboxed Worker-style threads, which cannot cause race conditions). Any engine that did use multithreading to handle asynchronous code would fail to handle a vast amount of existing JS code; no one would reasonably expect code written for a single-threaded JS environment to work correctly in a multithreaded environment. Such an engine would likely also have to extend the language to include locking mechanisms and atomic operations.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top