为什么Javascript SetTimeout()不是多线程的 [英] why Javascript SetTimeout() is not multithreaded
问题描述
我有一个测试:
Html:
<div id="f1">Empty</div>
<div id="f2">Empty</div>
js:
var s1 = function() {
for (i = 1; i < 1000000000; i++) {
var b = i * i;
}
$('#f1').html('Set');
}
var s2 = function() {
if ($('#f1').html() == 'Empty') {
$('#f2').html('Multi Thread');
return;
};
$('#f2').html('One Thread');
}
setTimeout(s2,110);
setTimeout(s1,100);
有没有真正的理由为什么setTimeOut()不是在不同的线程中运行,而是像事件模型一样?
is there any real reason why setTimeOut() not run in different threads, instead like event model ?
推荐答案
Javascript本身不是多线程的,也不是非多线程的。但是,目前在主流浏览器中实现的Javascript的具体实现大多是单线程的。
Javascript is not multithreaded nor non-multithreaded per se. However, the specific implementations of Javascript that currently are implemented in major browsers mostly ARE single-threaded.
此外,对于正确的多线程,语言需要具有共享功能内存,锁,信号量和其他并发编程工具,当前定义的JavaScript没有(例如,没有办法描述并发JS线程如何控制谁更新DOM对象当然是共享的,因为那里有窗口中只有一个DOM)。
In addition, for proper multithreading, the language needs to have facilities for shared memory, locks, semaphors and other concurrent programming tools, which JavaScript as is currently defined does not have (for example, there is no way to describe how concurrent JS threads would control who gets to update DOM objects that are of course, shared since there's only one DOM in a window).
有人试图让JS更加并行化 - 看看网络工作者,英特尔的River Trail, Google的HTML5工作和更多。
There are attempts to make JS more parallelized - look at web workers, Intel's River Trail, Google's HTML5 work and more.
这篇关于为什么Javascript SetTimeout()不是多线程的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!