高级 base::

web worker

适用范围:

1. 作用:

  1. 使js可以使用多线程

2. 特点:

  • 完全异步

3. 缺点:

  • 在web worker线程中绝大多数浏览器api都不能够使用
    • 如window对象, dom操作

4. 场景:

  • 浏览器中实现js多线程

梗概:

web worker是html5标准规定的多线程api, 由浏览器实现

  1. 允许主线程创建worker线程, 主线程和worker会分开独立运行

视频讲解:

2分钟了解 Web Worker_哔哩哔哩_bilibili

指向原始笔记的链接

梗概

  • 每个worker实例对应一个js代码
    • 在worker对应的js代码定义woker的消息处理方法
    • 可向外部发送消息

过程

  1. 创建一个新的web worker对象:

    var worker = new Worker('worker.js');
  2. 在worker.js文件中编写要执行的代码:

    // worker.js
    // 定义接受信息的处理函数
    self.onmessage = function(e) {
        var result = doHeavyTask(e.data);
        // 对外发送消息
        self.postMessage(result);
    };
     
    function doHeavyTask(data) {
        // 执行耗时任务
        return result;
    }
  1. 主线程与web worker通信:
    • 发送消息给web worker:

      worker.postMessage(data);
    • 接收来自web worker的消息:

      worker.onmessage = function(e) {
          var result = e.data;
          // 处理来自worker的结果
      };

注意事项

  • Web workers不能访问DOM元素,无法操作页面上的元素。
  • Web workers之间无法直接通信,需要通过主线程进行消息传递。
  • Web workers不支持所有类型的JavaScript语法和API。

数据传输

  • 数据通信默认是值的深拷贝
    • 但也可以将二进制的引用比传递
      • 二进制的引用只能同时被一个线程所拥有
        • 避免脏写

示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Worker Demo</title>
</head>
<body>
    <h1>Web Worker Demo</h1>
 
    <p>Calculating Fibonacci sequence in the background...</p>
 
    <script>
        // Create a new web worker
        const worker = new Worker('worker.js');
 
        worker.onmessage = function(event) {
            console.log('Result from web worker:', event.data);
            document.body.innerHTML += '<p>Fibonacci sequence for n=20: ' + event.data + '</p>';
        };
 
        // Send a message to the web worker
        worker.postMessage(20);
    </script>
</body>
</html>
// worker.js
 
function fibonacci(n) {
    if (n <= 1) {
        return n;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}
 
self.onmessage = function(event) {
    console.log('Calculating Fibonacci sequence for n=' + event.data);
 
    const result = fibonacci(event.data);
 
    // Send the result back to the main thread
    self.postMessage(result);
};
Explanation:
- This code demonstrates how to use a web worker to perform a CPU-intensive task (calculating the Fibonacci sequence in this case) in the background without blocking the main thread.
- The HTML file creates a new web worker using `new Worker('worker.js')` and sends a message with the number 20 to be used as input for calculating the Fibonacci sequence.
- The `worker.js` file defines the logic for calculating the Fibonacci sequence recursively and listens for messages from the main thread using `self.onmessage`.
- Once the calculation is complete, the result is sent back to the main thread using `self.postMessage` and displayed on the webpage.