为什么Web Worker不能直接调用函数? [英] Why can't Web Worker call a function directly?

查看:1017
本文介绍了为什么Web Worker不能直接调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以像这样使用HTML5中的web worker:

We can use the web worker in HTML5 like this:

var worker = new Worker('worker.js');

但为什么我们不能调用这样的函数?

but why can't we call a function like this?

var worker = new Worker(function(){
    //do something
});


推荐答案

这就是网络工作者的设计方式。他们必须拥有自己的外部JS文件以及由该文件初始化的自己的环境。出于多线程冲突的原因,他们无法与常规的全局JS空间共享环境。

This is the way web workers are designed. They must have their own external JS file and their own environment initialized by that file. They cannot share an environment with your regular global JS space for multi-threading conflict reasons.

不允许Web工作者直接访问全局变量的一个原因是它需要在两个环境之间进行线程同步,这不是可用的东西(并且会使事情变得非常复杂)。当web worker有自己独立的全局变量时,除了通过与主JS线程正确同步的消息队列之外,它们不能搞乱主JS线程。

One reason that web workers are not allowed direct access to your global variables is that it would require thread synchronization between the two environments which is not something that is available (and it would seriously complicate things). When web workers have their own separate global variables, they cannot mess with the main JS thread except through the messaging queue which is properly synchronized with the main JS thread.

也许有一天更高级的JS程序员将能够使用传统的线程同步技术来共享对公共变量的访问,但是现在两个线程之间的所有通信都必须通过消息队列,并且Web worker无法访问主Javascript线程的环境。

Perhaps someday, more advanced JS programmers will be able to use traditional thread synchronization techniques to share access to common variables, but for now all communication between the two threads must go through the message queue and the web worker cannot have access to the main Javascript thread's environment.

这篇关于为什么Web Worker不能直接调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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