Javascript原子系列操作

时间:2015-04-23 09:16:01

标签: javascript concurrency atomic

给出以下javascript代码(或等效的代码):

var buf = [];
setInterval(function () {
  buf.push("token");
  // If buf has something pushed here we are screwed
  if (buf.length == 1) {
    sendCriticalLog();
  }
});

setInterval(function () {
  buf.push("other token");
});

有没有办法确保第一个区间的功能与buf有关?

我能提出的唯一方法是:

function atomic(lock, cb){
  var finish = function () {
    lock.callbacks = lock.callbacks.slice(1);
    if (lock.callbacks.length) {
      lock.callbacks[0].call();
    }
  };

  cb = cb.bind(null, finish);
  if ((lock.callbacks = (lock.callbacks || []).concat([cb])).length == 1) {
    // Nothing is running
    lock.callbacks[0]();
  };
}

var buf = [];
setInterval(function () {
  atomic(buf, function () {
    buf.push("token");
    // If buf has something pushed here we are screwed
    if (buf.length == 1) {
      sendCriticalLog();
    }
  });
});

setInterval(function () {
  atomic(buf, function () {
    buf.push("other token");
  });
});

但这是假设((lock.callbacks = (lock.callbacks || []).concat([cb])).length == 1)将保证以原子方式处理。例如,如果concat是用普通javascript编写的,那么这可能不起作用......

1 个答案:

答案 0 :(得分:1)

JavaScript不是多线程的,所以你的回调实际上已经是" atomic"。 buf只能在调用回调之间改变。