有没有办法在 JavaScript 中进行多线程处理?
14 回答
有关最新的支持信息,请参阅http://caniuse.com/#search=worker 。
以下是大约 2009 年的支持状态。
你想用谷歌搜索的词是JavaScript Worker Threads
除了Gears之外,目前还没有任何可用的东西,但是有很多关于如何实现它的讨论,所以我想请注意这个问题,因为答案无疑会在未来发生变化。
以下是 Gears 的相关文档:WorkerPool API
WHATWG 有一个工作线程的建议草案:Web Workers
还有 Mozilla 的DOM Worker Threads
更新: 2009 年 6 月,浏览器对 JavaScript 线程的支持的当前状态
Firefox 3.5有网络工作者。一些网络工作者的演示,如果你想看到它们的实际效果:
- 模拟退火(“试用”链接)
- 太空侵略者(链接在帖子末尾)
- MoonBat JavaScript 基准测试(第一个链接)
Gears 插件也可以安装在 Firefox 中。
Safari 4和WebKit nightlies都有工作线程:
Chrome内置了 Gears,因此它可以执行线程,尽管它需要用户的确认提示(并且它使用与 web worker 不同的 API,尽管它可以在任何安装了 Gears 插件的浏览器中工作):
- Google Gears WorkerPool Demo(不是一个很好的例子,因为它运行得太快而无法在 Chrome 和 Firefox 中进行测试,尽管 IE 运行它的速度很慢,以至于它会阻止交互)
IE8和IE9只能在安装了 Gears 插件的情况下执行线程
在 JavaScript 中执行多线程和异步的不同方法
在 HTML5 之前,JavaScript 只允许每页执行一个线程。
有一些 hacky 方法可以使用Yield、setTimeout()
、或事件处理程序来模拟异步执行(有关yield和的示例,请参见本文末尾setInterval()
)。XMLHttpRequest
setTimeout()
但是有了 HTML5,我们现在可以使用工作线程来并行执行函数。这是一个使用示例。
真正的多线程
多线程:JavaScript 工作线程
HTML5引入了 Web Worker Threads(参见:浏览器兼容性)
注意:IE9 及更早版本不支持。
这些工作线程是在后台运行而不影响页面性能的 JavaScript 线程。有关Web Worker的更多信息, 请阅读文档或本教程。
这是一个简单的示例,其中包含 3 个 Web Worker 线程,这些线程计数为 MAX_VALUE 并在我们的页面中显示当前计算值:
//As a worker normally take another JavaScript file to execute we convert the function in an URL: http://stackoverflow.com/a/16799132/2576706
function getScriptPath(foo){ return window.URL.createObjectURL(new Blob([foo.toString().match(/^\s*function\s*\(\s*\)\s*\{(([\s\S](?!\}$))*[\s\S])/)[1]],{type:'text/javascript'})); }
var MAX_VALUE = 10000;
/*
* Here are the workers
*/
//Worker 1
var worker1 = new Worker(getScriptPath(function(){
self.addEventListener('message', function(e) {
var value = 0;
while(value <= e.data){
self.postMessage(value);
value++;
}
}, false);
}));
//We add a listener to the worker to get the response and show it in the page
worker1.addEventListener('message', function(e) {
document.getElementById("result1").innerHTML = e.data;
}, false);
//Worker 2
var worker2 = new Worker(getScriptPath(function(){
self.addEventListener('message', function(e) {
var value = 0;
while(value <= e.data){
self.postMessage(value);
value++;
}
}, false);
}));
worker2.addEventListener('message', function(e) {
document.getElementById("result2").innerHTML = e.data;
}, false);
//Worker 3
var worker3 = new Worker(getScriptPath(function(){
self.addEventListener('message', function(e) {
var value = 0;
while(value <= e.data){
self.postMessage(value);
value++;
}
}, false);
}));
worker3.addEventListener('message', function(e) {
document.getElementById("result3").innerHTML = e.data;
}, false);
// Start and send data to our worker.
worker1.postMessage(MAX_VALUE);
worker2.postMessage(MAX_VALUE);
worker3.postMessage(MAX_VALUE);
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
我们可以看到三个线程是并发执行的,并在页面中打印出它们的当前值。它们不会冻结页面,因为它们是在后台使用分离的线程执行的。
多线程:具有多个 iframe
实现这一点的另一种方法是使用多个iframe,每个 iframe 将执行一个线程。我们可以通过 URL给iframe一些参数,并且iframe可以与他的父级通信以获得结果并打印回来(iframe必须在同一个域中)。
此示例不适用于所有浏览器! iframe通常在与主页相同的线程/进程中运行(但 Firefox 和 Chromium 似乎处理方式不同)。
由于代码片段不支持多个 HTML 文件,我将在这里提供不同的代码:
索引.html:
//The 3 iframes containing the code (take the thread id in param)
<iframe id="threadFrame1" src="thread.html?id=1"></iframe>
<iframe id="threadFrame2" src="thread.html?id=2"></iframe>
<iframe id="threadFrame3" src="thread.html?id=3"></iframe>
//Divs that shows the result
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
<script>
//This function is called by each iframe
function threadResult(threadId, result) {
document.getElementById("result" + threadId).innerHTML = result;
}
</script>
线程.html:
//Get the parameters in the URL: http://stackoverflow.com/a/1099670/2576706
function getQueryParams(paramName) {
var qs = document.location.search.split('+').join(' ');
var params = {}, tokens, re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params[paramName];
}
//The thread code (get the id from the URL, we can pass other parameters as needed)
var MAX_VALUE = 100000;
(function thread() {
var threadId = getQueryParams('id');
for(var i=0; i<MAX_VALUE; i++){
parent.threadResult(threadId, i);
}
})();
模拟多线程
单线程:使用 setTimeout() 模拟 JavaScript 并发
“天真的”方法是setTimeout()
一个接一个地执行函数,如下所示:
setTimeout(function(){ /* Some tasks */ }, 0);
setTimeout(function(){ /* Some tasks */ }, 0);
[...]
但是这种方法不起作用,因为每个任务都会一个接一个地执行。
我们可以通过递归调用函数来模拟异步执行,如下所示:
var MAX_VALUE = 10000;
function thread1(value, maxValue){
var me = this;
document.getElementById("result1").innerHTML = value;
value++;
//Continue execution
if(value<=maxValue)
setTimeout(function () { me.thread1(value, maxValue); }, 0);
}
function thread2(value, maxValue){
var me = this;
document.getElementById("result2").innerHTML = value;
value++;
if(value<=maxValue)
setTimeout(function () { me.thread2(value, maxValue); }, 0);
}
function thread3(value, maxValue){
var me = this;
document.getElementById("result3").innerHTML = value;
value++;
if(value<=maxValue)
setTimeout(function () { me.thread3(value, maxValue); }, 0);
}
thread1(0, MAX_VALUE);
thread2(0, MAX_VALUE);
thread3(0, MAX_VALUE);
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
正如你所看到的,第二种方法非常慢并且冻结了浏览器,因为它使用主线程来执行函数。
单线程:用 yield 模拟 JavaScript 并发
Yield是ECMAScript 6中的一项新功能,它仅适用于最旧版本的 Firefox 和 Chrome(在 Chrome 中,您需要启用出现在chrome://flags/#enable-javascript-harmony中的Experimental JavaScript)。
yield 关键字导致生成器函数执行暂停,并且 yield 关键字后面的表达式的值被返回给生成器的调用者。它可以被认为是 return 关键字的基于生成器的版本。
生成器允许您暂停函数的执行并在以后恢复它。生成器可用于使用称为蹦床的技术来安排您的功能。
这是示例:
var MAX_VALUE = 10000;
Scheduler = {
_tasks: [],
add: function(func){
this._tasks.push(func);
},
start: function(){
var tasks = this._tasks;
var length = tasks.length;
while(length>0){
for(var i=0; i<length; i++){
var res = tasks[i].next();
if(res.done){
tasks.splice(i, 1);
length--;
i--;
}
}
}
}
}
function* updateUI(threadID, maxValue) {
var value = 0;
while(value<=maxValue){
yield document.getElementById("result" + threadID).innerHTML = value;
value++;
}
}
Scheduler.add(updateUI(1, MAX_VALUE));
Scheduler.add(updateUI(2, MAX_VALUE));
Scheduler.add(updateUI(3, MAX_VALUE));
Scheduler.start()
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
JavaScript 中没有真正的线程。JavaScript 是一种具有延展性的语言,它确实允许您模拟其中的一些。这是我前几天遇到的一个例子。
Javascript 中没有真正的多线程,但您可以使用setTimeout()
异步 AJAX 请求获得异步行为。
你到底想完成什么?
这只是在Javascript中模拟多线程的一种方法
现在我要创建 3 个线程来计算数字加法,数字可以被 13 整除,数字可以被 3 整除,直到 10000000000。这 3 个函数不能与并发的含义同时运行。但我将向您展示一个技巧,该技巧将使这些函数同时递归运行:jsFiddle
这段代码属于我。
身体的一部分
<div class="div1">
<input type="button" value="start/stop" onclick="_thread1.control ? _thread1.stop() : _thread1.start();" /><span>Counting summation of numbers till 10000000000</span> = <span id="1">0</span>
</div>
<div class="div2">
<input type="button" value="start/stop" onclick="_thread2.control ? _thread2.stop() : _thread2.start();" /><span>Counting numbers can be divided with 13 till 10000000000</span> = <span id="2">0</span>
</div>
<div class="div3">
<input type="button" value="start/stop" onclick="_thread3.control ? _thread3.stop() : _thread3.start();" /><span>Counting numbers can be divided with 3 till 10000000000</span> = <span id="3">0</span>
</div>
Javascript 部分
var _thread1 = {//This is my thread as object
control: false,//this is my control that will be used for start stop
value: 0, //stores my result
current: 0, //stores current number
func: function () { //this is my func that will run
if (this.control) { // checking for control to run
if (this.current < 10000000000) {
this.value += this.current;
document.getElementById("1").innerHTML = this.value;
this.current++;
}
}
setTimeout(function () { // And here is the trick! setTimeout is a king that will help us simulate threading in javascript
_thread1.func(); //You cannot use this.func() just try to call with your object name
}, 0);
},
start: function () {
this.control = true; //start function
},
stop: function () {
this.control = false; //stop function
},
init: function () {
setTimeout(function () {
_thread1.func(); // the first call of our thread
}, 0)
}
};
var _thread2 = {
control: false,
value: 0,
current: 0,
func: function () {
if (this.control) {
if (this.current % 13 == 0) {
this.value++;
}
this.current++;
document.getElementById("2").innerHTML = this.value;
}
setTimeout(function () {
_thread2.func();
}, 0);
},
start: function () {
this.control = true;
},
stop: function () {
this.control = false;
},
init: function () {
setTimeout(function () {
_thread2.func();
}, 0)
}
};
var _thread3 = {
control: false,
value: 0,
current: 0,
func: function () {
if (this.control) {
if (this.current % 3 == 0) {
this.value++;
}
this.current++;
document.getElementById("3").innerHTML = this.value;
}
setTimeout(function () {
_thread3.func();
}, 0);
},
start: function () {
this.control = true;
},
stop: function () {
this.control = false;
},
init: function () {
setTimeout(function () {
_thread3.func();
}, 0)
}
};
_thread1.init();
_thread2.init();
_thread3.init();
我希望这种方式会有所帮助。
您可以使用Narrative JavaScript,一种将您的代码转换为状态机的编译器,有效地允许您模拟线程。它通过向允许您在单个线性代码块中编写异步代码的语言添加“yielding”运算符(标记为'->')来实现这一点。
今天应该出来的新v8引擎支持它(我认为)
在原始 Javascript 中,您可以做的最好的事情是使用少数异步调用 (xmlhttprequest),但这并不是真正的线程并且非常有限。 Google Gears为浏览器添加了许多 API,其中一些可用于线程支持。
如果您不能或不想使用任何 AJAX 东西,请使用 iframe 或十个!;) 您可以让进程在 iframe 中与母版页并行运行,而无需担心跨浏览器的类似问题或 dot net AJAX 等的语法问题,并且您可以从框架。
egFunction()
例如,在父 iframe 中,在 iframe 内容加载后调用父文档(这是异步部分)
parent.egFunction();
如果您愿意,也可以动态生成 iframe,以便主 html 代码不受它们的影响。
Javascript 没有线程,但我们有工人。
如果您不需要共享对象,worker 可能是一个不错的选择。
大多数浏览器实现实际上会将工作人员分布在所有内核上,从而允许您利用所有内核。你可以在这里看到一个演示。
我开发了一个名为task.js的库,它使这很容易做到。
task.js用于让 CPU 密集型代码在所有内核(node.js 和 web)上运行的简化接口
一个例子是
function blocking (exampleArgument) {
// block thread
}
// turn blocking pure function into a worker task
const blockingAsync = task.wrap(blocking);
// run task on a autoscaling worker pool
blockingAsync('exampleArgumentValue').then(result => {
// do something with result
});
使用 HTML5规范,您无需为此编写太多 JS 或找到一些技巧。
HTML5 中引入的功能之一是Web Workers,它是在后台运行的 JavaScript,独立于其他脚本,不会影响页面的性能。
几乎所有浏览器都支持它:
铬 - 4.0+
IE - 10.0+
Mozilla - 3.5+
野生动物园 - 4.0+
歌剧 - 11.5+
Topaz 是 .NET 的无锁多线程 Javascript 引擎:https ://github.com/koculu/topaz