Javascript并发控制 [英] Javascript Concurrency Control

查看:94
本文介绍了Javascript并发控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个教育项目,我在JavaScript中编写了另一个编辑器样式的实时语法高亮笔。

As an educational project, I'm writing (yet another) editor-style live syntax highlighter in JavaScript.

为了保持编辑器的响应性,我明显选择了荧光笔运行异步,然而对于我使用的模型,我需要能够终止一个荧光笔之前启动另一个如果在当前荧光笔完成之前键入的东西,并知道它在新的开始之前终止。

To keep the editor responsive I obviously opted to have the highlighter run asynchronously, however with the model I'm using I need to be able to terminate a highlighter before starting another if something is typed before the current highlighter finishes, and know that it's terminated before the new one starts.

我在想像做下面的事情:

I was thinking of doing something like the following:

var terminate = false;
var terminated = false;

function work() {
  while(!terminate)
    console.log('working');
  terminated = true;
}

function stop() {
  terminate = true;
  while(!terminated);
  console.log('stopped');
}

setTimeout(work, 0);
setTimeout(stop, 10);

然而这个例子不工作,我已经尝试使用更多的setTimeouts代替忙

This example however doesn't work, and I've tried using more setTimeouts in place of the busy waiting to no avail, either.

有没有办法在JavaScript中实现这样的系统,或者我应该使用一些替代(或两者)?

Is there a way to implement such a system in JavaScript or should I use some alternative (or both)?

推荐答案

如果你可以在没有DOM访问的情况下做很多工作,这将是完美的网络工作者。

If you can do much of your work without DOM access, this would be perfect for web workers.

要修正你的例子,尝试使用 setTimeout 0 产生控制。它的工作原理:

To fix your example, try yielding control using setTimeout with 0. This works:

var terminate = false;
var terminated = false;

function work() {
  if(!terminate) {
    console.log('working');
    setTimeout(work, 0);
  }
  else terminated = true;

}

function stop() {
  terminate = true;
  if(!terminated) {
      setTimeout(stop,0);
  }
  else console.log('stopped');
}

setTimeout(work, 0);
setTimeout(stop, 100);

编辑

解释你的原始代码片段的问题:Javascript是单线程的(除非你使用web worker)。你可以使用事件,回调和setTimeout来实现并发错觉,但是你真正做的是告诉运行时在单个执行线程上的某个时候执行你的回调函数。在你的情况下, stop 从来没有被执行。在10毫秒过期后,计划运行下一个(即工作完成后)。工作从不

To explain the problem with your original code snippet: Javascript is single-threaded (unless you are using web workers). You can use events, callbacks, and setTimeout to achieve an illusion of concurrency, but what you are really doing is telling the runtime to execute your callback function at some future time on the single execution thread. In your case, stop was never being executed. After the 10 ms expired, it was scheduled to run 'next' (i.e., after work finished. Since work never finished, stop could never run.

因此,任何明显的并发性,你想要从javascript中脱颖而出,你的工作线程将必须暂停,并明确允许其他东西发生,以维持错觉。

So any apparent concurrency you want to get out of javascript will be co-operative. Your worker thread will have to pause and explicitly allow "other stuff" to happen to maintain the illusion.

这篇关于Javascript并发控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆