什么是webworkers中的孤立线程?

时间:2013-12-10 08:52:58

标签: web-worker

什么是孤立的线程? 我在文章后面找到了它。

Web Workers run in an isolated thread. As a result, the code that they execute needs to be contained in a separate file.

isolated thread

通常,线程是进程的子集。所以我想知道他们是如何孤立的?

1 个答案:

答案 0 :(得分:2)

它们是孤立的,因为它们不与主页面的JavaScript共享相同的JavaScript全局执行上下文。他们可以与页面的主(UI)JavaScript进行交互的唯一方法是发送和接收消息(postMessage和相关的message事件)。

这是一个证明工人在不同的全球背景下运作的例子:

page.html

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Isolated Worker</title>
</head>
<body>
<script>
// A global variable
var answer = 42;
(function() {

    // We see answer
    display("UI: typeof answer = " + typeof answer);

    // Worker doesn't
    var worker = new Worker("worker.js");
    worker.onmessage = function(e) {
        display(e.data);
    };

    function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
    }
})();
</script>
</body>
</html>

worker.js

this.postMessage("Worker: typeof answer = " + typeof answer);

输出:

UI: typeof answer = number
Worker: typeof answer = undefined

正如您所看到的,工作者无法看到主页的全局变量;他们处于不同的全球执行环境中。