js中的worker使用及多线程改单线程实现

一、Worker

  • 使用

    • 创建worker实例

      var worker = new Worker(url); // 创建Worker对象

      只会执行url指定的脚本,必须同源

    • 主线程

      // 监听接收worker线程信息
      worker.onmessage = (e) => console.log(`接收到worker传递的信息:${e.data}`);
      // 发送信息到worker线程
      worker.postMessage('内容');

      传递的数据类型包含:String、Number、Object、Array等JavaScript标准类型。

    • worker线程

      // 监听接收主线程信息
      self.onmessage = (e) => console.log(`接收到主线程发送的信息:${e.data}`);
      // 发送信息到主线程
      self.postMessage('内容');

      在子线程中,self代表worker子线程的全局对象,也可以用this代替self,或者省略也行。

    • 销毁worker线程

      worker.terminate() // 在主线程中关闭
    • 子线程自己关闭

      self.close()
  • 示例

    • 主线程

      // 创建Worker对象实例
      var worker = new Worker('worker.js');
      
      // 监听并接收worker线程消息
      worker.onmessage = (e) => {
          console.log(`收到worker线程消息:${e.data}`);
          work.terminate(); // 销毁worker线程
      };
      
      // 向worker线程发送消息
      worker.postMessage('hello worker')
    • worker线程(worker.js)

      // 监听并接收主线程发送的消息(省略self的写法)
      onmessage = (e) => {
          console.log(`收到主线程消息:${e.data}`); 
          //向主线程发送消息
          postMessage('你好,我是worker!');
      }
    • 服务端

      // 导入express
      const express = require('express')
      
      // 创建Web服务器
      const app = express()
      
      // 调用express.static()方法,快速对外提供静态资源
      app.use(express.static(__dirname))
      
      app.listen(8080, () => {
          console.log('express server running at http://127.0.0.1:8080')
      })

      启动服务端,浏览器访问http://127.0.0.1:8080即可,index.html页面中加载主线程js代码即可

二、改写多线程为单线程执行

  • 代码

    // btoa、atob方法实现
    !function(){
        // private property
        _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
        // public method for encoding
        this.btoa = function (input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = _utf8_encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output +
                    _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                    _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
            }
            return output;
        }
    
        // public method for decoding
        this.atob = function (input) {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
            while (i < input.length) {
                enc1 = _keyStr.indexOf(input.charAt(i++));
                enc2 = _keyStr.indexOf(input.charAt(i++));
                enc3 = _keyStr.indexOf(input.charAt(i++));
                enc4 = _keyStr.indexOf(input.charAt(i++));
                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;
                output = output + String.fromCharCode(chr1);
                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }
            }
            output = _utf8_decode(output);
            return output;
        }
    
        // private method for UTF-8 encoding
        _utf8_encode = function (string) {
            string = string.replace(/\r\n/g, "\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
    
            }
            return utftext;
        }
    
        // private method for UTF-8 decoding
        _utf8_decode = function (utftext) {
            var string = "";
            var i = 0;
            var c, c1, c2, c3;
            c = c1 = c2 = 0;
            while (i < utftext.length) {
                c = utftext.charCodeAt(i);
                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                } else if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                } else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        }
    }()
    
    // 主线程
    function Worker(jscode){
        // 与之关联的子线程
        this.self = new Worker_self(atob(jscode))
    
        // 子线程与主线程关联
        this.self.main = this
    }
    Worker.prototype.onmessage = undefined;
    Worker.prototype.addEventListener = function (type, func, x){
        switch (type){
            case 'message':
                this.onmessage = func;
                break
            default:
                break
        }
    }
    Worker.prototype.postMessage = function (msg){
        return this.self.onmessage({data: msg})
    }
    Worker.prototype.terminate = function (){
    }
    
    // 子线程
    function Worker_self(jscode){
        let self = this;
        let window = self;
        let globalThis = self;
        eval(jscode)
    }
    Worker_self.prototype.onmessage = undefined
    Worker_self.prototype.main = undefined
    Worker_self.prototype.postMessage = function (msg){
        return this.main.onmessage({data: msg})
    }
    Worker_self.prototype.addEventListener = function (type, func, x){
        switch (type){
            case 'message':
                this.onmessage = func;
                break
            default:
                break
        }
    }
    Worker_self.prototype.close = function (){}
    View Code
  • 注意事项

    • 在原有主线程代码前面,添加以上部分代码,手动实现Worker
    • new Worker()实例化Worker对象时,不再传入url地址,而是经过base64编码后的子线程相关源码(子线程中统一采用self或者this这种写法,视情况补充改写)
posted @ 2023-04-23 03:16  eliwang  阅读(1060)  评论(0编辑  收藏  举报