Why can't Web Worker call a function directly?

前端 未结 7 1041
借酒劲吻你
借酒劲吻你 2021-02-01 03:15

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?



        
相关标签:
7条回答
  • 2021-02-01 03:44

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题